Click here to Skip to main content
14,210,288 members
Click here to Skip to main content
Technical Blog
Posted 28 Aug 2017

Tagged as

Stats

124.6K views
8 bookmarked

Upload/Download Files in ASP.NET Core 2.0

,
Rate this:
3.53 (10 votes)
Please Sign up or sign in to vote.
3.53 (10 votes)
28 Aug 2017     CPOL    
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:

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:

[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:

<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:

// 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:

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:

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)

Share

About the Author

Tahir Naushad
Software Developer (Senior)
United Kingdom United Kingdom
Qualified and skilled professional with experience working as a Software Developer, Technical Lead and Architect. I have worked on windows, web and distributed applications using the latest set of technologies within the Microsoft .NET ecosystem. I have lead teams using agile methodologies and trained developers in writing well-designed and maintainable software applications.

Currently focusing on C#, ASP.NET Core, EF, JavaScript, React, Azure, Domain Driven Design and Microservices.

Comments and Discussions

 
Questionfile upload Pin
amit9051030-Aug-18 20:53
memberamit9051030-Aug-18 20:53 
QuestionHow to upload multiple files? Pin
Member 1396414527-Aug-18 22:36
memberMember 1396414527-Aug-18 22:36 
QuestionHow to Remove Files From wwwroot ? Pin
Member 1353982524-Jul-18 0:28
memberMember 1353982524-Jul-18 0:28 
Questionmemorystream Pin
Todd Sprang22-Jun-18 2:50
memberTodd Sprang22-Jun-18 2:50 
Questionupload files from main host to download host + asp mvc Pin
farshadt206-Jun-18 23:05
memberfarshadt206-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
memberbNobo3421-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
membermccaber826-Dec-17 21:52 
QuestionThanks!! Pin
pbright22-Nov-17 6:30
memberpbright22-Nov-17 6:30 
QuestionVery good tutorial, but.. Pin
Member 1129535322-Oct-17 23:51
memberMember 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
memberDewey28-Aug-17 8:26 
AnswerRe: Thanks, have a 5 Pin
Tahir Naushad28-Aug-17 11:42
memberTahir Naushad28-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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190618.1 | Last Updated 28 Aug 2017
Article Copyright 2017 by Tahir Naushad
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid