Uploading files with ASP.NET Core 1.0 MVC

4.61 (23 votes)

Handling file uploads has changed quite a bit in ASP.NET Core. This article looks at the new objects that have been introduced to replace the old System.Web based approach from previous versions of ASP.NET. **Updated to RTM**

In previous versions of ASP.NET, an uploaded file was represented by an instance of System.Web.HttpPostedFileBase. This has been replaced in ASP.NET Core by IFormFile, which is found in the Microsoft.AspNet.Http namespace. It shares a few of the same properties and methods as its predecessor, but it also has its differences, as can best be shown by example.

First, here's an upload form that uses the new TagHelpers introduced in ASP.NET Core MVC:

<form method="post" asp-action="Index" asp-controller="Home" enctype="multipart/form-data">
    <input type="file" name="files" multiple/>
    <input type="submit" value="Upload" />
</form>

To enable file uploading, you need to ensure that the form's method is set to post and that the enctype is set to multipart/form-data. This example takes advantage of the HTML5 multiple attribute on the file input which enables multiple file uploading via a single control.

file upload

The form posts back to the Index method on the Home controller:

public class HomeController : Controller
{
    private IHostingEnvironment _environment;

    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }
    public IActionResult Index()
    {
        return View();
    }

    [HttpPost]
    public async Task<IActionResult> Index(ICollection<IFormFile> files)
    {
        var uploads = Path.Combine(_environment.WebRootPath, "uploads");
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(Path.Combine(uploads, file.FileName), FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
            }
        }
        return View();
    }
}

The controller has a constructor added that takes an IHostingEnvironment as a parameter. IHostingEnvironment is a service that provides some useful environment information such as the current file path to the wwwroot folder via the WebRootPath property. This is required when specifying the location for saving uploaded files. One version of the Index method is restricted to supporting HTTP Post operations and it takes a collection of IFormFile objects as a parameter. The name of the parameter is the same as the name attribute provided to the file upload in the HTML form ("files") so that model binding will take care of matching uploaded files to the method parameter.

IFormFile objects share some properties and methods with their predecessors. IFormFile objects have a Length property instead of ContentLength. The FileName property was added in RC2. Before that, you had to parse the ContentDisposition headers to obtain that information. Note that in RC2, there is also a Name property. This actually returns the value of the name attribute on the upload control. Having obtained the actual file name, the code saves the uploaded file to the specified location asynchronously using the CopyToAsync method. This was added in RC2, replacing a SaveAsAsync method.

Summary

Handling uploaded files in ASP.NET Core is a little different to previous versions. This article explored the new APIs and provided a brief overview of the properties and methods of most interest.

A sample application is available at Github.

You might also like...

Date Posted:
Last Updated:
Posted by:
Total Views to date: 54488

11 Comments

- Jerrie Pelser

Your post is a day late ;) Struggled with this one yesterday, and it turned out I forgot (or rather did not know about) the enctype attribute which needs to be set,

Thanks for doing the post Mike :)

- Johann

Could you provide the model for the upload code, i have been struggling to scaffold IFormFile as part of the model in a code first approach. I am using RC1 of ASP.NET5.

- Lee

I upload files to Azure Storage use this method:

blockBlob.UploadFromStream(fileStream)

but in asp.net 5 ,IFormFile only have a SaveAs() method, how can i upload the file to Azure?

waiting for your help!!

- Mike

@Lee,

I don't use Azure so I don't know anything about it.

- Andrey Kurdyumov

@Lee IFormFile has OpenReadStream(): Stream method

- Arthur

Thanks for your article buuuut ..... what dependencies am I supposed to pull in my controller ?

- Mike

@Arthur

You don't actually need any in order to work with uploads. I injected IHostingEnvironment so I could get access to a file path.

- Adrian Barrera

Buen artículo.

- Sergio

Do you know how can i limit the number of files than the user can upload, and how can i limit the size and extensions of the files?

And Thanks for your post, it was very helpful for me.

- Derek Gabriel

Minor error in your code, the return needs to be moved outside the for each loop so that it will compile (as is not all code paths return a value) and if you left it and add another return outside the loop you will only get one file if you have multiple selected.

- Mike

@Derek,

Thanks for pointing that out. Not sure how it slipped through, but I've fixed it now.

Recent Comments

Gfw 03/02/2017 09:48
In response to Free SSL Certificates On IIS With LetsEncrypt
I have used WinSimple for about the last 9 months - works great. One thing that you want to make of...

Ted Driver 02/02/2017 13:24
In response to Free SSL Certificates On IIS With LetsEncrypt
This looks great is you have command line access to your web server - what about those of us on Is...

Carl T. 06/11/2016 05:43
In response to Server.MapPath Equivalent in ASP.NET Core
Very succinct and easy to follow. Worked perfectly the first time for me. Thanks!!...

Manoj Kulkarni 04/11/2016 05:47
In response to Entity Framework Core DbContext Updated
Great post....

Sivu 19/10/2016 08:21
In response to Entity Framework Core TrackGraph For Disconnected Data
Oh that's very very very nice ! Thanks for the write up Mike, much appreciated for the taking the to...

Mark 12/10/2016 16:42
In response to ASP.NET Web Pages vNext or Razor Pages
Although "Web Pages" was removed from the roadmap, has it just been renamed to "Razor Pages"?...

Satyabrata 12/10/2016 09:20
In response to Entity Framework Core TrackGraph For Disconnected Data
Nice article. Please write more articles featuring ASP.Net web pages. Thank you...

Julian 26/09/2016 14:27
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Fantastic, many thanks Mike! Had got half way down this road before finding your article - saved...

Abolfazl Roshanzamir 14/09/2016 05:36
In response to Loading ASP.NET Core MVC Views From A Database Or Other Location
Nice article. Thanke you so much ....

cyrus 02/09/2016 15:12
In response to ASP.NET Web Pages vNext or Razor Pages
I've got some news. As Damian stated in this link: https://github.com/aspnet/Mvc/issues/5208 “We...