【问题标题】:How to download file in asp.net core如何在 asp.net core 中下载文件
【发布时间】:2018-07-14 22:48:17
【问题描述】:

我的下载方式是

public async Task<IActionResult> Download(string filename)
        {

            if (filename == null)
                return Content("filename not present");

            var path = Path.Combine(
                           Directory.GetCurrentDirectory(), "wwwroot" + @"\UploadFiles", 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));
        }

和 view.chtml 和带有文件路径的路由

<a asp-action="Download"
                   asp-route-filename="@item.UploadFilePath">
                    Download
                </a> 

@item.UploadFilePath 是数据库保存的路径。请帮助我。

【问题讨论】:

  • 为什么要标记javascript jquery
  • 那你有什么问题?

标签: asp.net-mvc asp.net-core-1.1


【解决方案1】:

你也可以试试这个

return File(path, MediaTypeNames.Application.Octet, Path.GetFileName(path));

【讨论】:

  • 老师好,我上面的代码在本地运行下载正常,但是 iis 服务器上传和下载问题。为什么.....
【解决方案2】:

你可以试试这个,

byte[] fileBytes = System.IO.File.ReadAllBytes(Filepath);
return File(fileBytes, "application/x-msdownload", FileName);

【讨论】:

    【解决方案3】:

    使用此代码从 wwwroot 下载文件

     public IActionResult DownloadAttachment(string attachment)
        {
            var path = Path.Combine(
               Directory.GetCurrentDirectory(), "wwwroot\\UploadFile\\Journal",attachment);
            byte[] fileBytes = System.IO.File.ReadAllBytes(path);
            return File(fileBytes, "application/x-msdownload", attachment);
        }
    

    【讨论】:

      【解决方案4】:

      在网址/Files?fileName=image.png上试试这个,文件image.png必须放在wwwroot中。

      public class FilesModel : PageModel
      {
          private readonly IWebHostEnvironment hostingEnvironment;
      
          public FilesModel(IWebHostEnvironment hostingEnvironment)
          {
              this.hostingEnvironment = hostingEnvironment;
          }
      
          public PhysicalFileResult OnGet(string fileName)
          {
              string path = Path.Combine(hostingEnvironment.WebRootPath, "Files", fileName);
              return new PhysicalFileResult(path, "image/png"); // Change to the right mime type
          }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-15
        • 1970-01-01
        • 2020-02-07
        • 2022-02-01
        相关资源
        最近更新 更多