通过显示“另存为对话”导出文件

问题描述 投票:-1回答:1
string fileName = "1001-1000-1_29_2015 2_04_22 PM.wav";
string filePath = Server.MapPath("Audio") + "\\" + fileName;

在IE中,我使用以下行导出我的.wav文件。

Response.Redirect("Audio/" + fileName);

由于Response.Redirect();用于将用户重定向到任何东西(页面,文件等)。因此在IE中它向用户显示SaveAsDialogue以保存它。

但在chrome中,浏览器的默认行为是重定向到指定的文件并在chrome中播放。

我想通过在两个浏览器中提供.wav来导出我的SaveAsDialogue文件。

我为chrome尝试了以下代码:

Response.Clear();
Response.ContentType = "Audio/wav";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.Flush();
Response.End();

但是我仍然无法在Chrome中传输我的.wav文件。

c# asp.net google-chrome internet-explorer savefiledialog
1个回答
2
投票

这样就可以了;通过将内容的mime类型更改为通用内容:

Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=" + fileName);
Response.TransmitFile(filePath);
Response.Flush();
Response.End();

编辑:这是我正在使用的确切代码,它也适用于WAV文件:

Response.Clear();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename="+ fileName);
Response.WriteFile(file);
Response.End();

保存到对话是客户端功能,不能强制*。 IE首先提供它的唯一原因是因为它在尝试直接访问文件时不知道如何处理该文件。上面的方法是强制它下载,而不是直接在浏览器中播放/渲染。但是,您可以右键单击链接并选择Save link as...

*我想如果你在服务器上为文件类型错误地设置mime类型然后使用你原来的Response.Redirect方法,那么你可以但是你会弄乱服务器并且不会导致头痛的结束。

如果您想更改Chrome以便每次向您询问何处保存下载内容,您需要进入“设置”,单击“显示高级设置...”,然后向下滚动到“下载”标题,您将看到以下内容:

© www.soinside.com 2019 - 2024. All rights reserved.