How to upload and download File using MVC - Free Asp.Net,MVC,AngularJs,Jquery,Javascript,Sql Server,WCF,Entity framework snippets and tutorial

How to upload and download File using MVC

In this article I am going to explain how to upload and download File using MVC.

How to upload and download File using MVC


 Description:
I want to upload multiple files and can download them.  I want to save the file path to database and file to server.

Implementation:
 I have created a table tb_file.

Id
int
FileName
varchar(200)
Filepath
varchar(MAX)

Add a new MVC project.  I am using database first approach. Add entity data model for project.

Model (Tb_file.cs):

   public partial class Tb_File
    {
        public int Id { get; set; }
        public string FileName { get; set; }
        public string Filepath { get; set; }
    }


Add Controller
Now add an empty controller. Create action to upload file and download file.

Complete code of Controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using MVC_Project.Models;
using System.IO;
namespace MVC_Project.Controllers
{
  
    public class FileController : Controller
    {
        DemoEntities1 db = new DemoEntities1();
        public ActionResult Index()
        {
            return View();          
        }
      
 [HttpPost]
        public ActionResult Index(IEnumerable<HttpPostedFileBase> files, Tb_File objfile)
        {
            foreach (var file in files)
            {
                if (file != null && file.ContentLength > 0)
                {
                    var fileName = Path.GetFileName(file.FileName);
                    var filepath = Guid.NewGuid().ToString() + fileName;
                    var path = Path.Combine(Server.MapPath("~/uploads"), filepath);
                    file.SaveAs(path);
                    objfile.FileName = fileName;
                    objfile.Filepath = "~/uploads/" + filepath;
                    db.Tb_File.Add(objfile);
                    db.SaveChanges();
                }
            }
            return View();
        }
       
   //download
 public ActionResult Download()
        {
            var file = db.Tb_File.ToList();
            return View(file);
        }
        
 public FileResult DownloadFile(string id)
        {
            int fid = Convert.ToInt32(id);
            string filename = (from f in db.Tb_File
                               where f.Id == fid
                               select f.Filepath).First();
            return File(filename, System.Net.Mime.MediaTypeNames.Application.Octet, filename);
        }

        }
            }


Add View
Now add view for Index and download action.

Index.cshtml:
@{
    ViewBag.Title = "Upload File's";
}                  
   @using (Html.BeginForm("", "", FormMethod.Post, new { enctype = "multipart/form-data" }))
                      {
                          <table>
                              <tr>
                                  <td>Upload File :</td>
                                  <td><input type="file" name="files" multiple="multiple" /></td>
                              </tr>
                              <tr>
                                  <td></td>
                                  <td></td>
                              </tr>
                              <tr>
                                  <td></td>
                                  <td><input type="submit" value="Upload File" /></td>
                              </tr>
                          </table>
                      }



Download.cshtml

@model IEnumerable<MVC_Project.Models.Tb_File>

@{
    ViewBag.Title = "Download";
}

<table class="table">
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.FileName)
        </th>
        <th>           
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.FileName)
        </td>
        <td></td>
        <td>
            @Html.ActionLink("Download", "DownloadFile", new { id = item.Id })
        </td>
    </tr>
}
</table>

Now build the project and run. To test it upload files and download them.



What do you think about this article?

If you found this article useful, please share and follow on Facebook, Twitter, Google Plus and other social media websites. To get free updates subscribe to newsletter. Please put your thoughts and feedback in comments section.

Share this

Share on FacebookTweet on TwitterPlus on Google+


EmoticonEmoticon