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

Step-1

In an empty project, replace or update the Startup class to add service 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?}");  
        });  
    }  

Step-2

Add a Controller and action method to add and download the 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));  
  } 

Step-3

Add a new Razor page with HTML form to upload a 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 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  
[HttpPost]  
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; }  
 }  
 [HttpPost]  
 public async Task<IActionResult> UploadFileViaModel(FileInputModel model)  

Note

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.

Downloading

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  
officedocument.spreadsheetml.sheet"},  
                {".png", "image/png"},  
                {".jpg", "image/jpeg"},  
                {".jpeg", "image/jpeg"},  
                {".gif", "image/gif"},  
                {".csv", "text/csv"}  
            };  
        } 
0 Shares:
Leave a Reply

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

twenty − 5 =

You May Also Like
Twelve-Factor Application of Microservices
Read More

The Twelve-Factor App

Introduction In the current era, software program is usually delivered as a service: referred to as net apps,…