Site icon ParallelCodes

MVC – How to Upload and Download Files in ASP.NET MVC Tutorial

Hi friends,
In this post let’s see how we can upload and download files in ASP.NET MVC C#. For upload and download files only in ASP.NET, please see this post. This example will be quite simple. We will enter the file name and select the file which we want to upload and submit it. The file will be first saved in the “UploadFiles” files folder on the server and its path will be saved in the SQL database table. On viewing the Page, a MVC table will be represented with uploaded file to download it directly. So let’s start. Final page will be like below:DOWNLOAD SOURCE CODE

First, please create a table and SQL stored procedure to save our uploaded file path in Database.

DBScript:

CREATE TABLE [dbo].[tblFiles](
[Id] [int] IDENTITY(1,1) NOT NULL,
[FileN] [nvarchar](50) NULL,
[FilePath] [nvarchar](max) NULL
)
----------------------------

CREATE procedure [dbo].[sp_AddFiles]
(
@FileN nvarchar(50),@FilePath nvarchar(max)
)
as begin
Insert into tblFiles (FileN,FilePath) values (@FileN,@FilePath)
end
-------------------------------

Now create a new Model class in your MVC project with name Products and edit it as below:

Products.cs:

using MVCFiles.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Web.Mvc;

namespace MVCFiles.Controllers
{
public class ProductsController : Controller
{
SqlConnection con;
SqlDataAdapter adapter;
SqlCommand cmd;
static String connectionString = @"Data Source=VIBES;Initial Catalog=ParallelCodes;User ID=sa;Password=789;Integrated Security=True;";
// GET: Products
public ActionResult Index()
{
Products products = GetProducts();
ViewBag.Message = "";
return View(products);
}

public void DownloadFile(String file)
{
try
{
String filename = file;
String filepath = Server.MapPath("~/UploadedFile/" + filename);

Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.AddHeader("Content-Disposition", "attachment; filename=" + filename);
Response.Flush();

Response.TransmitFile(filepath);
Response.End();
// HttpContext.ApplicationInstance.CompleteRequest();
ViewBag.Message = "";
}
catch (Exception ex)
{
ViewBag.Message = ex.Message.ToString();
}

}

[HttpPost]
public ActionResult Index(Products obj)
{
try
{
string strDateTime = System.DateTime.Now.ToString("ddMMyyyyHHMMss");
string finalPath = "\\UploadedFile\\" + strDateTime + obj.UploadFile.FileName;

obj.UploadFile.SaveAs(Server.MapPath("~") + finalPath);
obj.FilePath = strDateTime + obj.UploadFile.FileName;
ViewBag.Message = SaveToDB(obj);
}
catch (Exception ex)
{
ViewBag.Message = ex.Message.ToString();
}

Products products = GetProducts();
return View(products);
}

public string SaveToDB(Products obj)
{
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandText = "sp_AddFiles";
cmd.Parameters.AddWithValue("@FileN", obj.FileN);
cmd.Parameters.AddWithValue("@FilePath", obj.FilePath);
cmd.ExecuteNonQuery();

cmd.Dispose();
con.Dispose();
con.Close();

return "Saved Successfully";
}
catch (Exception ex)
{
return ex.Message.ToString();
}
}

public Products GetProducts()
{
Products products = new Products();
try
{
con = new SqlConnection(connectionString);
cmd = new SqlCommand("Select * from tblFiles", con);
con.Open();
adapter = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
adapter.Fill(dt);

adapter.Dispose();
cmd.Dispose();
con.Close();

products.lstProducts = new List<Products>();

foreach (DataRow dr in dt.Rows)
{
products.lstProducts.Add(new Products
{
FileN = dr["FileN"].ToString(),
FilePath = dr["FilePath"].ToString()
});
}

}
catch (Exception ex)
{
adapter.Dispose();
cmd.Dispose();
con.Close();
}

if (products == null || products.lstProducts == null || products.lstProducts.Count == 0)
{
products = new Products();
products.lstProducts = new List<Products>();
}

return products;
}
}
}

Create a view for the Index method and edit it as below:

Views>Products>Index.cshtml:

@model MVCFiles.Models.Products

@{
Layout = null;
}

<!DOCTYPE html>

<html>
<head>
<meta name="viewport" content="width=device-width" />
<link href="~/Content/bootstrap.css" rel="stylesheet" />
<title>Index</title>
</head>

<body style="padding:5px;">
@using (Html.BeginForm("Index", "Products", FormMethod.Post, new
{ enctype = "multipart/form-data" }))
{
@Html.AntiForgeryToken()
<h1>
MVC File Upload & Download Example
</h1>
<hr />
<div>
<table class="table-condensed">
<tr>
<td>
File Name:
</td>
<td>
@Html.TextBoxFor(m => m.FileN)
</td>
</tr>
<tr>
<td>
File:
</td>
<td>
<input type="file" name="UploadFile" required />
</td>
</tr>
<tr>
<td>
<input type="submit" name="submit" value="Submit" />
</td>
</tr>
<tr>
<td colspan="3">
@ViewBag.Message
</td>
</tr>
</table>
</div>

<div>
<table class="table-condensed table-bordered">
<tr>
<th align="center">
File Name
</th>
<th align="center">
File
</th>
<th align="center">
Download File
</th>
</tr>

@foreach (var product in Model.lstProducts)
{
<tr>
<td align="center">
@product.FileN
</td>
<td align="center">
@product.FilePath
</td>

<td align="center">
<a class="btn btn-default"
href="http://localhost/MVCFiles/Products/DownloadFile?file=@product.FilePath"
target="_blank">
<b>Download</b>
</a>
</td>
</tr>
}
</table>
</div>
}
<div>
</div>
</body>
</html>

Now run your MVC project. Open the Products controller to view the upload and download page.

DOWNLOAD SOURCE CODE

mvc-file-upload-download-tutorial

 

Also see:

How to upload files in ASP.NET?

How to upload files in ASP.NET MVC C#?

ASP.NET How to download files?

How to upload and download files in ASP.NET with SQL Database?


Exit mobile version