Click here to Skip to main content
15,886,071 members
Articles / Web Development / ASP.NET / ASP.NET Core

Upload/Download Files in ASP.NET Core 2.0

Rate me:
Please Sign up or sign in to vote.
3.78/5 (12 votes)
28 Aug 2017CPOL 179.8K   8   16
How to upload and download files in ASP.NET Core MVC. Continue reading...

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:

C#
public void ConfigureServices(
            IServiceCollection services)
        {
            services.AddSingleton<IFileProvider>(
                new PhysicalFileProvider(
                    Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));

            services.AddMvc();
        }

        public void Configure(
            IApplicationBuilder app,
            IHostingEnvironment env)
        {
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });
        }

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

C#
[HttpPost]
        public async Task<IActionResult> UploadFile(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return Content("file not selected");

            var path = Path.Combine(
                        Directory.GetCurrentDirectory(), "wwwroot", 
                        file.GetFilename());

            using (var stream = new FileStream(path, FileMode.Create))
            {
                await file.CopyToAsync(stream);
            }

            return RedirectToAction("Files");
        }

        public async Task<IActionResult> Download(string filename)
        {
            if (filename == null)
                return Content("filename not present");

            var path = Path.Combine(
                           Directory.GetCurrentDirectory(),
                           "wwwroot", filename);

            var memory = new MemoryStream();
            using (var stream = new FileStream(path, FileMode.Open))
            {
                await stream.CopyToAsync(memory);
            }
            memory.Position = 0;
            return File(memory, GetContentType(path), Path.GetFileName(path));
        }

Add a razor page with HTML form to upload file:

HTML
<form asp-controller="Home" asp-action="UploadFile" method="post"
      enctype="multipart/form-data">
    
    <input type="file" name="file" />
    <button type="submit">Upload File</button>
</form>

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:

C#
// In Controller
[HttpPost]
public async Task<IActionResult> UploadFiles(List<IFormFile> files)

// In HTML
<input type="file" name="files" multiple />

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

C#
public class FileInputModel
    {
        public IFormFile FileToUpload { get; set; }
    }
    [HttpPost]
    public async Task<IActionResult> UploadFileViaModel(FileInputModel model)

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:

C#
private string GetContentType(string path)
        {
            var types = GetMimeTypes();
            var ext = Path.GetExtension(path).ToLowerInvariant();
            return types[ext];
        }

        private Dictionary<string, string> GetMimeTypes()
        {
            return new Dictionary<string, string>
            {
                {".txt", "text/plain"},
                {".pdf", "application/pdf"},
                {".doc", "application/vnd.ms-word"},
                {".docx", "application/vnd.ms-word"},
                {".xls", "application/vnd.ms-excel"},
                {".xlsx", "application/vnd.openxmlformats
                           officedocument.spreadsheetml.sheet"},
                {".png", "image/png"},
                {".jpg", "image/jpeg"},
                {".jpeg", "image/jpeg"},
                {".gif", "image/gif"},
                {".csv", "text/csv"}
            };
        }

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionIm getting c:\fakepath Pin
Tresa Britto4-May-21 3:04
Tresa Britto4-May-21 3:04 
QuestionNeed download razor / javascript / ajax code! Also, here's how to get content type without a 'quick and dirty' method Pin
IdahoTaterHead26-Jul-19 9:55
IdahoTaterHead26-Jul-19 9:55 
I'm having trouble figuring out how to get file download to work. The tutorial only shows an action method, not the client side code and markup.

And, here's how to get the content (mime) type without writing your own helper method:

C#
using Microsoft.AspNetCore.StaticFiles; // For FileExtensionContentTypeProvider

namespace FileProject
{
    public static class FileHelper 
    {
        public static string GetMimeType(string fileName)
        {
            var provider = new FileExtensionContentTypeProvider();
            if (!provider.TryGetContentType(fileName, out var mimeType))
            {
                mimeType = "application/octet-stream";
            }

            return mimeType;
        }
    }
}


Brian
Questionfile upload Pin
amit9051030-Aug-18 20:53
amit9051030-Aug-18 20:53 
QuestionHow to upload multiple files? Pin
Member 1396414527-Aug-18 22:36
Member 1396414527-Aug-18 22:36 
QuestionHow to Remove Files From wwwroot ? Pin
Member 1353982524-Jul-18 0:28
Member 1353982524-Jul-18 0:28 
Questionmemorystream Pin
Todd Sprang22-Jun-18 2:50
Todd Sprang22-Jun-18 2:50 
Questionupload files from main host to download host + asp mvc Pin
farshadt206-Jun-18 23:05
farshadt206-Jun-18 23:05 
Questionhow about downloading from other urls? Pin
MrSadin24-May-18 11:46
professionalMrSadin24-May-18 11:46 
QuestionHow to handle large files ? Pin
bNobo3421-Mar-18 7:11
bNobo3421-Mar-18 7:11 
AnswerRe: How to handle large files ? Pin
MrSadin24-May-18 11:33
professionalMrSadin24-May-18 11:33 
QuestionContent Type Pin
mccaber826-Dec-17 21:52
mccaber826-Dec-17 21:52 
QuestionThanks!! Pin
pbright22-Nov-17 6:30
pbright22-Nov-17 6:30 
QuestionVery good tutorial, but.. Pin
Member 1129535322-Oct-17 23:51
Member 1129535322-Oct-17 23:51 
AnswerRe: Very good tutorial, but.. Pin
MrSadin24-May-18 11:34
professionalMrSadin24-May-18 11:34 
QuestionThanks, have a 5 Pin
Dewey28-Aug-17 8:26
Dewey28-Aug-17 8:26 
AnswerRe: Thanks, have a 5 Pin
User 104326428-Aug-17 11:42
User 104326428-Aug-17 11:42 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.