asp.net-mvc ASP.NET MVC FileStreamResult,未使用 fileDownloadName

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15862683/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 02:43:33  来源:igfitidea点击:

ASP.NET MVC FileStreamResult, fileDownloadName is not used

asp.net-mvcpdf-generationfilestreamresult

提问by user1620141

The following returns a PDF which the browser tries to directly display inline. This works correctly. However, if I try to download the file, the download name is not "myPDF.pdf", but instead the ID in the route (myapp/controller/PDFGenerator/ID). Is it possible to set the file download name to be "myPDF.pdf"?

以下返回浏览器尝试直接内联显示的 PDF。这工作正常。但是,如果我尝试下载文件,下载名称不是“myPDF.pdf”,而是路径中的 ID (myapp/controller/PDFGenerator/ID)。是否可以将文件下载名称设置为“myPDF.pdf”?

public FileStreamResult PDFGenerator(int id)
{
    MemoryStream ms = GeneratePDF(id);

    byte[] file = ms.ToArray();
    MemoryStream output = new MemoryStream();
    output.Write(file, 0, file.Length);
    output.Position = 0;
    HttpContext.Response.AddHeader("content-disposition", 
    "inline; filename=myPDF.pdf");

    return File(output, "application/pdf", fileDownloadName="myPDF.pdf");
}

回答by Darin Dimitrov

No, this is not possible with a PDF displayed inline. You could achieve this if you send the Content-Disposition header with as an attachment:

不,内联显示的 PDF 无法做到这一点。如果您将 Content-Disposition 标头作为附件发送,则可以实现此目的:

public ActionResult PDFGenerator(int id)
{
    Stream stream = GeneratePDF(id);
    return File(stream, "application/pdf", "myPDF.pdf");
}

Also notice how I removed the unnecessary MemoryStreamyou were using and loading the PDF in memory where you could have directly streamed it to the client which would have been far more efficient.

还要注意我如何删除MemoryStream您正在使用的不必要的内容并将 PDF 加载到内存中,您可以直接将其流式传输到客户端,这样效率会更高。

回答by Nalan Madheswaran

If you are using FileStreamResult to download the file, try using this in controller

如果您使用 FileStreamResult 下载文件,请尝试在控制器中使用它

Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", "attachment; filename=FileName.pdf");

回答by F Snyman

It is possible by making the id a string which represents the file name without the extension.

可以通过使 id 成为代表没有扩展名的文件名的字符串。

public ActionResult PDFGenerator(string id, int? docid)
{
    Stream stream = GeneratePDF(docid);
    return new FileStreamResult(stream , "application/pdf");
}

The url then then end like this

网址然后像这样结束

  ..PDFGenerator/Document2?docid=15