Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

pdf generation - ASP.NET MVC FileStreamResult, fileDownloadName is not used

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");
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...