ASP.NET MVC FileStreamResult,不使用fileDownloadName

编程入门 行业动态 更新时间:2024-10-25 13:25:18
本文介绍了ASP.NET MVC FileStreamResult,不使用fileDownloadName的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

下面返回该浏览器尝试直接显示内嵌的PDF文件。这正常工作。但是,如果我尝试下载该文件,下载的名称不是myPDF.pdf,而是在路由(MyApp的/控制器/的pdfGenerator / ID)的ID。是否有可能设置文件下载名称为myPDF.pdf?

公共FileStreamResult的pdfGenerator(INT ID){    的MemoryStream毫秒​​= GeneratePDF(ID);    字节[] =文件ms.ToArray();    MemoryStream的输出=新的MemoryStream();    output.Write(文件,0,file.Length);    output.Position = 0;    HttpContext.Response.AddHeader(内容处置,    内联;文件名= myPDF.pdf);    返回文件(输出应用程序/ PDF,fileDownloadName =myPDF.pdf);}

解决方案

没有,这是不可能用PDF内嵌显示。你可以做到这一点,如果你发送的内容处理标头作为附件:

公众的ActionResult的pdfGenerator(INT ID){    流流= GeneratePDF(ID);    返回文件(流应用程序/ PDF,myPDF.pdf);}

还要注意我如何删除不必要的的MemoryStream 你正在使用和加载在内存中的PDF在那里你可以把它直接传输到客户端这将有更为高效

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

解决方案

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.

更多推荐

ASP.NET MVC FileStreamResult,不使用fileDownloadName

本文发布于:2023-11-17 03:29:48,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1608656.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:NET   ASP   MVC   fileDownloadName   FileStreamResult

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!