如何通过ASP.NET codebehind强制Chrome在下载文件时打开“打开文件对话框”?

9
我有一个页面,可以发送二进制文件、PDF、Word或Excel到Web浏览器。在Firefox和IE中,都会打开一个对话框,询问您想要使用此文件做什么,“打开”或“保存”。
但是Chrome直接将其保存到您的计算机上。
是否有可能在将文件发送到浏览器之前,在Web响应中放置一些元数据,以使Chrome询问您想要使用此文件做什么?
3个回答

14

无法强制Chrome提示保存对话框,用户必须在Chrome的(高级设置)中更改该行为。

输入图像描述


那个设置在哪里? - Valentin Despa
但是要求用户勾选此复选框并不实际,那么是否有其他解决方案呢? - Nithin Paul

0

也许这会有所帮助

System.String filePath = "c:\\tempFile.pdf"
System.IO.FileInfo fileInfo = new FileInfo(filePath);

System.Web.HttpContext context = System.Web.HttpContext.Current;
System.Web.HttpResponse response = context.Response;
response.Clear();
response.ClearHeaders();
response.ClearContent();
response.ContentType = "application/pdf";
response.AppendHeader("content-type", "application/pdf");
response.AppendHeader("content-length", fileInfo.Length.ToString());
response.AppendHeader("content-disposition", String.Format("attachment; filename={0}.pdf", outputFileName));
response.TransmitFile(filePath);
response.Flush(); // this make stream and without it open chrome save dialog
context.ApplicationInstance.CompleteRequest(); // send headers and c# server-side code still continue

System.IO.File.Delete(filePath); // clean cache here if you need

response.End();

0

你需要发送一些头信息,这样浏览器才知道如何处理你正在流式传输的内容,例如:

Response.ContentType 
Content-Disposition, application,and 
filename=" + FileName

这将强制下载。更多信息请参阅此链接:

http://www.devtoolshed.com/aspnet-download-file-web-browser

谢谢


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接