Upload and Download Files In ASP.NET Core 2.0

Upload and Download Files In ASP.NET Core 2.0
Upload and Download Files In ASP.NET Core 2.0


In an empty project, replace or update the Startup class to add service and middleware for MVC.

public void ConfigureServices(  
        IServiceCollection services)  
            new PhysicalFileProvider(  
                Path.Combine(Directory.GetCurrentDirectory(), "wwwroot")));  
    public void Configure(  
        IApplicationBuilder app,  
        IHostingEnvironment env)  
        app.UseMvc(routes =>  
                name: "default",  
                template: "{controller=Home}/{action=Index}/{id?}");  


Add a Controller and action method to add and download the file.

  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",   
      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(  
                     "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 new Razor page with HTML form to upload a file.

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

Discussion Uploading

ASP.NET Core MVC model binding gives IFormFile interface to add one or greater files. The HTML structure have to have the encoding kind set to multipart/form-data and an enter factor with type attribute set to file.

You should additionally add a couple of files through receiving a listing of IFormFile in method.

// In Controller  
public async Task<IActionResult> UploadFiles(List<IFormFile> files)  
// In HTML  
<input type="file" name="files" multiple /> 

You ought to additionally have IFormFile as a property on model acquired through the action method.

public class FileInputModel  
     public IFormFile FileToUpload { get; set; }  
 public async Task<IActionResult> UploadFileViaModel(FileInputModel model)  


The title on enter input elements should same action parameter identify (or model property name) for model binding to work. This is no exceptional than model binding of easy and complex types.


Action approach wishes to return FileResult with both a stream, byte[], or virtual path of the files. You will additionally want to understand the content-type of the file being downloaded. Here is a pattern (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  
                {".png", "image/png"},  
                {".jpg", "image/jpeg"},  
                {".jpeg", "image/jpeg"},  
                {".gif", "image/gif"},  
                {".csv", "text/csv"}  
Leave a Reply

Your email address will not be published. Required fields are marked *

20 + seventeen =

You May Also Like