Click here to Skip to main content
14,831,710 members
Articles / Web Development / ASP.NET / ASP.NET Core
Technical Blog
Posted 28 Aug 2017

Tagged as

Stats

166.7K views
8 bookmarked

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

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 cloud applications using the latest set of technologies. I have lead teams using agile methodologies and trained developers in writing well-designed, maintainable and secure software applications.

Comments and Discussions

 
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
MemberIdahoTaterHead26-Jul-19 9:55 
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.