Uploading files with ASP.NET Core 1.0 MVC

4.61 (28 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: 82055

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

Pam 30/08/2017 11:30
In response to Sending Email in Razor Pages
Mike, RazorPages sound like a nice choice for somebody still working in ASP classic who wants to to...

Robby Robson 15/08/2017 00:43
In response to Routing in Razor Pages
Mike: great stuff. Now that .Core Standard 2.0 is formally out, how soon will you rewrite your book...

Satyabrata Mohapatra 28/07/2017 08:59
In response to Sending Email in Razor Pages
Bit off topic, but congratulation sir for your MVP award. You deserve it !!!...

Satyabrata Mohapatra 23/07/2017 16:43
In response to Razor Pages - The Elevator Pitch
@Dale Severin You can continue to build apps using asp.net web pages....

Satyabrata Mohapatra 23/07/2017 16:40
In response to Sending Email in Razor Pages
Thanks for sharing...learned a lot...

Gfw 22/07/2017 11:53
In response to Sending Email in Razor Pages
Question... Does System.Net.Mail support SSL?...

Dale Severin 20/07/2017 03:38
In response to Razor Pages - The Elevator Pitch
I work with razor web pages extensively. I appreciate the rapid development it permits me to I am as...

Obinna Okafor 14/07/2017 01:19
In response to Routing in Razor Pages
Thank you, Mike. Good post....

Satyabrata Mohapatra 11/07/2017 16:02
In response to Routing in Razor Pages
Very powerful routing system!!...

Cyrus 05/07/2017 03:41
In response to Razor Pages - Getting Started With The Preview
How can I trim packages and services as much as possible to use just razor pages? I don’t want to to...