如何在asp.net核心下载文件

时间:2018-02-05 05:42:59

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

我的下载方法是

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是数据库保存的路径。请帮助我。

4 个答案:

答案 0 :(得分:2)

你可以试试这个,

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

答案 1 :(得分:1)

你也可以尝试这个

function clearFilter() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var ssId = ss.getId();
  var sheetIds = ss.getSheets();
  for (var i in sheetIds) {
    var requests = [{
      "clearBasicFilter": {
        "sheetId": sheetIds[i].getSheetId()
      }
    }];
    Sheets.Spreadsheets.batchUpdate({'requests': requests}, ssId); 
  }
}

答案 2 :(得分:0)

在URL /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
    }
}

答案 3 :(得分:0)

使用此代码从 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);
    }