javascript - Content-Disposition 附件是否被 XMLHttpRequest 阻止?

标签 javascript content-disposition

我想从我编写的 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 。 我得到以下响应

The headers obtained in the response, with Firebug

我确保在 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-Dispositionimg 元素的处理有什么影响(如果有的话):

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/

相关文章:

javascript - 使用字符串调用变量

javascript - 向纯 React 组件添加事件处理程序?

javascript - node.js:如何在尝试解析内容之前等到 "unzip"完成

python - 如何在 django 应用程序中使用 FileResponse.set_headers() 来启用 .mp3 文件下载

internet-explorer - IE 和内容处置内联与扩展 token

javascript - 两个部分的 HTML 不同样式

java - 如何强制 sevlet 将字符串作为附件发送到浏览器?

c# - 内容处置文件名不适用于 IE

javascript - QScriptEngine中如何定义 `window`对象