如何在ASP.NET代码隐藏下载文件时强制Chrome打开“打开文件对话框”?

时间:2012-12-18 12:55:08

标签: c# asp.net google-chrome httpresponse

我有一个页面,它将binari文件,pdf,word或excel发送到Web浏览器。在firefox中,IE都打开一个对话框,询问你对这个文件做了什么,“打开”或“保存”

enter image description here

Chrome 会直接将其保存到您的计算机上。

是否可以让Chrome问你想用这个文件做什么,在将文件发送到浏览器之前将一些元数据放入网页回复?

3 个答案:

答案 0 :(得分:10)

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

enter image description here

答案 1 :(得分:0)

您需要发送一些标题,以便浏览器知道如何处理您正在流式传输的内容:

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

会强行下载。有关更多信息,请参阅此链接:

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

由于

答案 2 :(得分: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();
相关问题