How to download a file in ASP.NET Core

后端 未结 9 1966
离开以前
离开以前 2020-12-02 13:14

In MVC, we have used following code to download a file. In ASP.NET core, how to achieve this?

HttpResponse response = HttpContext.Current.Response;                   


        
9条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-02 13:48

    my way is quite short and I think it suits most people's need.

      [HttpPost]
      public ActionResult Download(string filePath, string fileName)
      {
          var fileBytes = System.IO.File.ReadAllBytes(filePath);
          new FileExtensionContentTypeProvider().TryGetContentType(Path.GetFileName(filePath), out var contentType);
          return File(fileBytes, contentType ?? "application/octet-stream", fileName);
      }
    

提交回复
热议问题