AspNetCore下载(导出)文件

22 浏览
0 Comments

AspNetCore下载(导出)文件

在我的一个.NET Framework 4.5项目中,我按照以下方式创建响应(文件下载)。

.NET Framework 4.5版本:

public virtual HttpResponseMessage ExportExcel()
{
    ...................
    ....................
    HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
    Stream stream = new MemoryStream(bytes);
    response.Content = new StreamContent(stream);
    var cookie = new CookieHeaderValue("customValue", "true");
    cookie.Path = "/";
    response.Headers.AddCookies(new CookieHeaderValue[] { cookie });
    response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
    {
        FileName = ExportFileName
    };
    return response;
}

如您所见,我添加了cookie,Header ContentType等。

这是我移植到.NET Core的版本:

public virtual ActionResult ExportExcel()
{
    ........
    .......
    byte[] bytes = _svc.Export(excelTemplatePath, ExcelColumns);
    Response.StatusCode = 200;
    Response.Cookies.Append("customValue", "true");
    Response.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet").ToString();
    return File(bytes, "application/x-msdownload", "");
}

问题:

1-我找不到设置ContentDisposition的方法。

2-.Net Core中没有Response.Content(我找不到Response.Content = new StreamContent(stream))。

0
0 Comments

AspNetCore download (export) file这个问题的出现的原因是想要在AspNetCore中实现文件的下载(导出)功能,但是代码中缺少设置Content-Disposition的部分,导致下载的文件没有指定文件名。

解决方法是在代码中添加Content-Disposition的设置,具体实现如下:

public IActionResult ExportExcel()
{
    FileStreamResult fsr = null;
    string excelPath = @"C:\Temp\Excel.xls";
    try
    {
        var filename = Path.GetFileName(excelPath);
        Stream tempFileStream = new FileStream(excelPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
        fsr = new FileStreamResult(tempFileStream, MimeHelper.GetMimeType(filename));
        fsr.FileDownloadName = filename; // 设置下载的文件名
    }
    catch (Exception e)
    {
        Log.Error(e, "Failed to read: {FILE}", excelPath);
        return fsr;
    }
    return fsr;
}

通过添加fsr.FileDownloadName = filename;这一行代码,将下载的文件名设置为原始文件的文件名,这样就可以正确地实现文件的下载功能了。

0