Is Content-Disposition attachment blocked from XMLHttpRequest?

前端 未结 1 1201
盖世英雄少女心
盖世英雄少女心 2020-12-09 21:31

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/         


        
相关标签:
1条回答
  • 2020-12-09 22:17

    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.

    0 讨论(0)
提交回复
热议问题