File Upload And Download Using ASP.NET MVC 5 For Beginners

Introduction

 
In this article, we will learn how to upload or download a single file into a folder in ASP.NET MVC 5. First, we have to create a table for the stored file's info, like name, and create a path to the database.
 

Create Table

 
Open SQL Server to create a database with any suitable name and then create a table.
 
Here, I am using DemoTest as the database name and tblFileDetails as the table name.
 
Table Structure
  1. CREATE TABLE [dbo].[tblFileDetails](  
  2.     [SQLID] [int] IDENTITY(1,1) NOT NULL,  
  3.     [FILENAME] [nvarchar](500) NULL,  
  4.     [FILEURL] [nvarchar](1500) NULL  
  5. )   

Creating MVC Application

 
Now, I am going to create a sample application. Open Visual Studio. Go to File->New->Project. Give FileUploadDownload as project name or give a suitable name to the application. Click OK.
 
File Upload And Download Using ASP.NET MVC 5 For Beginners
 
Now, select MVC as a template and then click OK.
 
File Upload And Download Using ASP.NET MVC 5 For Beginners
 
Now we add a folder to the application where we store all uploaded files and name it as UploadedFiles.
 
We have created a project called “FileUploadDownload“ and now, we are going to add a Model class for file upload.
 
Right-click on “MODELS” folder and add a class name as "FileUpload".
 
Add the below code to FileUpload model class.
 
Code for FileUpload.cs
  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.   
  6. namespace FileUploadDownload.Models  
  7. {  
  8.     public class FileUpload  
  9.     {  
  10.         public string FileId { getset; }  
  11.         public string FileName { getset; }  
  12.         public string FileUrl { getset; }  
  13.         public IEnumerable<FileUpload> FileList { getset; }  
  14.     }  
  15. }  
After adding Model class now we add a controller to the Controller folder.
 
Right-click on the controller. Add->Controller.
 
Select MVC 5 Controller as Empty. Click Add.
 
Give “FilesController” name to the controller.
 
Add the below code to the controller.
 
Code of FilesController
  1. using System;  
  2. using System.IO;  
  3. using System.Web;  
  4. using System.Data;  
  5. using System.Web.Mvc;  
  6. using System.Data.SqlClient;  
  7. using System.Collections.Generic;  
  8. using FileUploadDownload.Models;  
  9.   
  10. namespace FileUploadDownload.Controllers  
  11. {  
  12.     public class FilesController : Controller  
  13.     {  
  14.         string conString = "Data Source=.;Initial Catalog =DemoTest; integrated security=true;";  
  15.   
  16.         // GET: Files  
  17.         public ActionResult Index(FileUpload model)  
  18.         {  
  19.             List<FileUpload> list = new List<FileUpload>();  
  20.             DataTable dtFiles = GetFileDetails();  
  21.             foreach (DataRow dr in dtFiles.Rows)  
  22.             {  
  23.                 list.Add(new FileUpload  
  24.                 {  
  25.                     FileId = @dr["SQLID"].ToString(),  
  26.                     FileName = @dr["FILENAME"].ToString(),  
  27.                     FileUrl = @dr["FILEURL"].ToString()  
  28.                 });  
  29.             }  
  30.             model.FileList = list;  
  31.             return View(model);  
  32.         }  
  33.   
  34.         [HttpPost]  
  35.         public ActionResult Index(HttpPostedFileBase files)  
  36.         {  
  37.             FileUpload model = new FileUpload();  
  38.             List<FileUpload> list = new List<FileUpload>();  
  39.             DataTable dtFiles = GetFileDetails();  
  40.             foreach (DataRow dr in dtFiles.Rows)  
  41.             {  
  42.                 list.Add(new FileUpload  
  43.                 {  
  44.                     FileId = @dr["SQLID"].ToString(),  
  45.                     FileName = @dr["FILENAME"].ToString(),  
  46.                     FileUrl = @dr["FILEURL"].ToString()  
  47.                 });  
  48.             }  
  49.             model.FileList = list;  
  50.   
  51.             if (files != null)  
  52.             {  
  53.                 var Extension = Path.GetExtension(files.FileName);  
  54.                 var fileName = "my-file-" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Extension;  
  55.                 string path = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);  
  56.                 model.FileUrl = Url.Content(Path.Combine("~/UploadedFiles/", fileName));  
  57.                 model.FileName = fileName;  
  58.   
  59.                 if (SaveFile(model))  
  60.                 {  
  61.                     files.SaveAs(path);  
  62.                     TempData["AlertMessage"] = "Uploaded Successfully !!";  
  63.                     return RedirectToAction("Index""Files");  
  64.                 }  
  65.                 else  
  66.                 {  
  67.                     ModelState.AddModelError("""Error In Add File. Please Try Again !!!");  
  68.                 }  
  69.             }  
  70.             else  
  71.             {  
  72.                 ModelState.AddModelError("""Please Choose Correct File Type !!");  
  73.                 return View(model);  
  74.             }  
  75.             return RedirectToAction("Index""Files");  
  76.         }  
  77.   
  78.         private DataTable GetFileDetails()  
  79.         {  
  80.             DataTable dtData = new DataTable();  
  81.             SqlConnection con = new SqlConnection(conString);  
  82.             con.Open();  
  83.             SqlCommand command = new SqlCommand("Select * From tblFileDetails", con);   
  84.             SqlDataAdapter da = new SqlDataAdapter(command);  
  85.             da.Fill(dtData);  
  86.             con.Close();  
  87.             return dtData;  
  88.         }  
  89.   
  90.         private bool SaveFile(FileUpload model)  
  91.         {  
  92.             string strQry = "INSERT INTO tblFileDetails (FileName,FileUrl) VALUES('" +  
  93.                 model.FileName + "','" + model.FileUrl + "')";  
  94.             SqlConnection con = new SqlConnection(conString);  
  95.             con.Open();  
  96.             SqlCommand command = new SqlCommand(strQry, con);  
  97.             int numResult = command.ExecuteNonQuery();  
  98.             con.Close();  
  99.             if (numResult > 0)  
  100.                 return true;  
  101.             else  
  102.                 return false;  
  103.         }  
  104.     }  
  105. }  
After adding controller now we add a view to the controller.
 
For that right click on Index ActionResult. Go to Add View.
 
Then Select the empty template. Click add.
 
As you click on the Add button in Views-->File folder, the Index.cshtml file will be created.
 
Now, let's modify the Index.cshtml code.
 
Add the below code to Index.cshtml
 
Code for Index.cshtml
  1. @model FileUploadDownload.Models.FileUpload  
  2.   
  3. @{  
  4.     ViewBag.Title = "File Upload & Download";  
  5. }  
  6.   
  7. @using (Html.BeginForm("Index""Files", FormMethod.Post, new { enctype = "multipart/form-data" }))  
  8. {  
  9.     @Html.AntiForgeryToken()  
  10.     <div class="row">  
  11.         <div class="col-md-10">  
  12.             <h2>File Upload</h2>  
  13.             <hr />  
  14.             @Html.ValidationSummary(true""new { @class = "text-danger" })  
  15.   
  16.             <div class="form-group">  
  17.                 <label class="col-md-2 control-label">Upload Image</label>  
  18.                 <div class="col-md-10">  
  19.                     <input type="file" id="files" name="files" class="form-control" required="required"><br />  
  20.                 </div>  
  21.             </div>  
  22.   
  23.             <div class="form-group">  
  24.                 <div class="col-md-offset-2 col-md-10">  
  25.                     <input type="submit" value="Upload" class="btn btn-default" />  
  26.                 </div>  
  27.             </div>  
  28.         </div>  
  29.     </div>  
  30. }  
  31.   
  32. <div class="row">  
  33.     <div class="col-md-10">  
  34.         <h2>Uploaded File Details</h2>  
  35.         <div class="form-group">  
  36.             <div>  
  37.                 @{  
  38.                     var grid = new WebGrid(source: Model.FileList, canPage: true, rowsPerPage: 15);  
  39.                     @grid.GetHtml(tableStyle: "table table-striped table-bordered table-hover", headerStyle: "webgrid-header",  
  40.                         alternatingRowStyle: "webgrid-alternating-row", selectedRowStyle: "webgrid-selected-row",  
  41.                         footerStyle: "webgrid-footer", rowStyle: "webgrid-row-style", mode: WebGridPagerModes.All,  
  42.                         firstText: "<< First", previousText: "< Prev", nextText: "Next >", lastText: "Last >>",  
  43.                         htmlAttributes: new { id = "DataTable" },  
  44.                         columns: grid.Columns(  
  45.                             grid.Column("FileName", header: "FILE NAME", canSort: false),  
  46.                             grid.Column("FileUrl", header: "FILE PATH", canSort: false),  
  47.                             grid.Column(header: "DOWNLOAD", format:  
  48.                                 @<text>  
  49.                                         <a href="~/Files/[email protected]"><img src="~/Images/download.png" style="width: 15px; height: 15px" title="Download" /></a>  
  50.                                 </text>)  
  51.                          ));  
  52.                 }  
  53.             </div>  
  54.         </div>  
  55.     </div>  
  56. </div>  
  57.   
  58. @section Scripts {  
  59.     @Scripts.Render("~/bundles/jqueryval")  
  60. }  
Now, we add the DownloadFile option to the controller. Switch to FilesController and add the below code.
 
Code for Download file
  1. public ActionResult DownloadFile(string filePath)  
  2. {  
  3.     string fullName = Server.MapPath("~" + filePath);  
  4.   
  5.     byte[] fileBytes = GetFile(fullName);  
  6.     return File(  
  7.         fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, filePath);  
  8. }  
  9.   
  10. byte[] GetFile(string s)  
  11. {  
  12.     System.IO.FileStream fs = System.IO.File.OpenRead(s);  
  13.     byte[] data = new byte[fs.Length];  
  14.     int br = fs.Read(data, 0, data.Length);  
  15.     if (br != fs.Length)  
  16.         throw new System.IO.IOException(s);  
  17.     return data;  
  18. }  
Now, build and run the project. It looks like the below image.
 
File Upload And Download Using ASP.NET MVC 5 For Beginners
 
Now, choose a file and click on Upload. It will save the file to the UploadedFiles folder as well as save the data to the database.
 
For downloading the file, click on the "Download" image and it will download the particular file.
 
File Upload And Download Using ASP.NET MVC 5 For Beginners
 
We have just learned how to upload and download the file in ASP.NET MVC. I hope this post is useful for beginners. Happy Coding.


Similar Articles