File Upload in ASP.NET Core and MVC 6

 

        Introduction:

 

                 In beta 3 version of ASP.NET Core (vNext), uploading and saving file(s) become very easy. In other words, ASP.NET Core now support model binding of multipart form data. So, now we can easily upload and save file(s).  In this article, I will show you a sample to how to upload and save file(s) in ASP.NET Core.

 

        Description:

 

                    Assuming that you are running Visual Studio 2015 CTP 6 (you can also get that from Azure VM) or later and you have created an ASP.NET Core web application. Add a html form and input type=form element in your mvc view,

 

    <form method="post" enctype="multipart/form-data">
        <input type="file" name="files" id="files" multiple />
	<input type="submit" value="submit" />
    </form>

 

                    Then inside your controller add these lines,

 

    public class HomeController : Controller
    {
        IApplicationEnvironment _hostingEnvironment;

        public HomeController(IApplicationEnvironment hostingEnvironment)
        {
            _hostingEnvironment = hostingEnvironment;
        }

        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public async Task<IActionResult> Index(IList<IFormFile> files)
        {
            foreach (var file in files)
            {
                var fileName = ContentDispositionHeaderValue
                    .Parse(file.ContentDisposition)
                    .FileName
                    .Trim('"');// FileName returns "fileName.ext"(with double quotes) in beta 3

                if (fileName.EndsWith(".txt"))// Important for security if saving in webroot
                {
                    var filePath = _hostingEnvironment.ApplicationBasePath + "\\wwwroot\\"+ fileName;
                    await file.SaveAsAsync(filePath);
                }
            }
            return RedirectToAction("Index");// PRG
        }

 

                    In the post method constructor, I am passing IList<IFormFile>(files) as a parameter which will be model bind by the framework. Then for each file in files I am getting file name by parsing file.ContentDisposition using ContentDispositionHeaderValue.Parse method. In beta 3 file name is in quotes (look like a bug) that's why I am trimming double quotes. I am also checking file extension (important for security reasons). Then I am saving the file using IFormFile.SaveAsAsync method.

 

 

                   

        Summary:

                    ASP.NET Core beta 3 makes it very easy to upload and save file(s). In this article, I showed you, how to upload and save file(s) in ASP.NET Core.

No Comments