سؤال

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");
هل كانت مفيدة؟

المحلول

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.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top