我想从我编写的 C# 网络服务器对 png 文件执行 javascript xhr 请求。 这是我使用的代码
var imgUrl = "http://localhost:8085/AnImage.png?" + now;
var request = new XMLHttpRequest();
request.open('GET', imgUrl, false);
request.send(); // this is in a try/catch
在服务器端,我发回文件并添加一个 Content-Disposition header 。 我得到以下响应
我确保在 Content-Type 之后的标题中附加了 Content-Disposition(屏幕截图来自 Firebug,它按字母顺序附加)。
结果是没有对话框被触发,我是不是在响应中遗漏了什么?
编辑: 出于多种原因,我想在 javascript 中执行所有操作。 第一:我不想展示形象,我想把一切都藏在幕后。 第二:请求图像时,我希望仅在特定请求时添加 Content-Disposition。此类请求标有值为“AttachmentRequest”的“警告” header
request.setRequestHeader("Warning","AttachmentRequest");
最佳答案
我不认为 Content-Disposition
在请求通过 XHR 时触发任何文件保存对话框。 XHR 的使用表明您将在代码中处理结果。
如果你希望提示用户将图像保存到文件中,我已经成功地使用了这个技术:
window.open("http://localhost:8085/AnImage.png?" + now);
它的缺点是它会短暂闪烁一个空白的打开窗口,直到标题到达,然后新窗口关闭并出现“保存文件”对话框。
使用 iframe
可以防止窗口闪烁:
var f = document.createElement('iframe');
f.style.position = "absolute";
f.style.left = "-10000px";
f.src = "http://localhost:8085/AnImage.png?" + now;
document.body.appendChild(f);
另外,我想知道 Content-Disposition
对 img
元素的处理有什么影响(如果有的话):
var img = document.createElement('img');
img.style.position = "absolute";
img.style.left = "-10000px";
img.src = "http://localhost:8085/AnImage.png?" + now;
document.body.appendChild(img);
我还没有尝试过,但是浏览器可能会尊重 header 。您需要确保在您想要支持的所有浏览器上进行测试。
关于javascript - Content-Disposition 附件是否被 XMLHttpRequest 阻止?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13929838/