Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
306 views
in Technique[技术] by (71.8m points)

javascript - Is Content-Disposition attachment blocked from XMLHttpRequest?

I want to perform a javascript xhr request for a png file from a C# webserver which I wrote. Here is the code I use

    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

On the server-side I send back the file and add a Content-Disposition header. I obtain the following response

The headers obtained in the response, with Firebug

I made sure that Content-Disposition was attached in the headers after the Content-Type (the screenshot is from Firebug, which appends in alphabetical order).

The results is that no dialog box is triggered, am I missing something in the response?

edit: I want to perform everything in javascript for several reasons. First: I don't want to show the image and I want to keep everything behind the curtain. Second: when requesting the image I want the Content-Disposition to be added only on particular requests. Such requests are marked with a "Warning" header with value "AttachmentRequest"

request.setRequestHeader("Warning","AttachmentRequest");
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...