繁体   English   中英

XMLHttpRequest 是否阻止了 Content-Disposition 附件?

[英]Is Content-Disposition attachment blocked from XMLHttpRequest?

我想从我编写的 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 标头。 我得到以下回复

在响应中获得的标头,使用 Firebug

我确保在 Content-Type 之后的标题中附加了 Content-Disposition(截图来自 Firebug,按字母顺序附加)。

结果是没有触发对话框,我是不是在响应中遗漏了什么?

编辑:出于多种原因,我想在 javascript 中执行所有操作。 第一:我不想展示图像,我想把一切都隐藏在幕后。 第二:在请求图像时,我希望仅在特定请求时添加 Content-Disposition。 此类请求标有“警告”标头,其值为“AttachmentRequest”

request.setRequestHeader("Warning","AttachmentRequest");

当请求是通过 XHR 时,我认为Content-Disposition不会触发任何文件保存对话框。 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);

我还没有尝试过,但浏览器可能会尊重标题。 您需要确保在您想要支持的所有浏览器上进行测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM