ASP.NET MVC FileStreamResult, fileDownloadName is not used

拈花ヽ惹草 提交于 2019-11-27 21:43:26

问题


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"?

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");
}

回答1:


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:

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

Also notice how I removed the unnecessary MemoryStream you 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.




回答2:


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

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



回答3:


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

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


来源:https://stackoverflow.com/questions/15862683/asp-net-mvc-filestreamresult-filedownloadname-is-not-used

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!