我有以下代码,这些代码实质上是将文件从一台服务器“代理”到另一台服务器。它在 IE 中完美运行,但 Firefox 似乎忽略了 Content-Type
header 并始终将文件 (MP3) 作为 text/html
传输。
这不是主要问题,但我想让它在所有浏览器中正常工作,所以有人可以提供帮助吗?另外,如果有更好/更有效的方法来完成此操作,请发布!
FileInfo audioFileInfo = new FileInfo(audioFile);
HttpWebRequest downloadRequest = (HttpWebRequest) WebRequest.Create(audioFile);
byte[] fileBytes;
using (HttpWebResponse remoteResponse = (HttpWebResponse) downloadRequest.GetResponse())
{
using (BufferedStream responseStream = new BufferedStream(remoteResponse.GetResponseStream()))
{
fileBytes = new byte[remoteResponse.ContentLength];
responseStream.Read(fileBytes, 0, fileBytes.Length);
Response.ClearContent();
// firefox seems to ignore this...
Response.ContentType = Utilities.GetContentType(audioFileInfo);
// ... and this
//Response.ContentType = remoteResponse.ContentType;
Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", audioFileInfo.Name));
Response.AddHeader("Content-Length", remoteResponse.ContentLength.ToString());
Response.BinaryWrite(fileBytes);
Response.End();
}
}
最佳答案
尝试在调用 ClearContents()
之前添加一个 Response.ClearHeaders()
,就像提到的 x2 并将文件作为 application/octet-stream
发送:
Response.ClearHeaders();
Response.ClearContent();
Response.ContentType = "application/octet-stream";
Response.AddHeader("Content-Disposition", "attachment; filename=\"blah\"");
...
当我需要将可下载文件(不一定是 mp3)传输到客户端时适合我。
关于c# - Firefox 忽略 Response.ContentType,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1345355/