Upload/Download Files in ASP.NET Core 2.0

Problem

How to upload and download files in ASP.NET Core MVC.

Solution

In an empty project update Startup class to add services and middleware for MVC:

Add a controller and action methods to upload and download file:

Add a razor page with HTML form to upload file:

Discussion

Uploading

ASP.NET Core MVC model binding provides IFormFile interface to upload one or more files. The HTML form must have encoding type set to multipart/form-data and an input element with type attribute set to file.

You could also upload multiple files by receiving a list of IFormFile in action method and setting input element with multiple attribute:

You could also have IFormFile as a property on model received by action method:

Note: name on input elements must match action parameter name (or model property name) for model binding to work. This is no different than model binding of simple and complex types.

Downloading

Action method needs to return FileResult with either a stream, byte[] or virtual path of the file. You will also need to know the content-type of the file being downloaded. Here is a sample (quick/dirty) utility method:

Source Code

GitHub: https://github.com/TahirNaushad/Fiver.Mvc.FileUpload

7 comments

  1. Thank You very much! Your code was pretty clear and helped me a lot.

    However, it doesn’t handle the file name properly when using google chrome, because it hides the full path, passing only the file name from the input field. I’ll branch your code from github and post my fixes as soon as possible.

  2. This is one of the better examples’ve seen. However, I really don’t want to pollute our pure HTML5 front ends with Razor C#. And I’m really against any kind of server side processing in a client app for deployment scalability reasons, as well as a maintaining a separation of concerns between skill sets needed for development.

    Thus I’m looking for this same example that strictly uses the multi-part form in HTML and calls the .Net Core API as a web service in a completely separate project/deployed component. Also, as a return type the service would likely need to return a JSON object and the return handled by a JavaScript listener.

    Thanks.

Leave a Reply