Is Content-Disposition attachment blocked from XMLHttpRequest?

有些话、适合烂在心里 提交于 2019-11-28 10:20:27

I don't think Content-Disposition triggers any file save dialog when the request is via XHR. The use of XHR suggests you're going to handle the result in code.

If you want the user to be prompted to save the image to a file, I've used this technique successfully:

window.open("http://localhost:8085/AnImage.png?" + now);

It has the downside that it flashes a blank open window briefly until the header arrives, then the new window closes and the "save file" dialog box appears.

Using an iframe may prevent the window flashing:

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);

Separately, I wonder what effect (if any) Content-Disposition has on the handling of an img element:

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);

I haven't tried that, but the browser might respect the header. You'd need to be sure to test on all of the browsers you want to support.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!