Download attribute with a file name not working?

前端 未结 2 875
生来不讨喜
生来不讨喜 2020-12-06 04:46

Download attribute is used to make browsers download the resource an anchor points to rather than navigate to it. And as an option, a new file name for the downloaded file c

相关标签:
2条回答
  • 2020-12-06 05:13

    This actually is possible with JavaScript, though browser support would be spotty. You can use XHR2 to download the file from the server to the browser as a Blob, create a URL to the Blob, create an anchor with its href property and set it to that URL, set the download property to whatever filename you want it to be, and then click the link. This works in Google Chrome, but I haven't verified support in other browsers.

    window.URL = window.URL || window.webkitURL;
    
    var xhr = new XMLHttpRequest(),
          a = document.createElement('a'), file;
    
    xhr.open('GET', 'someFile', true);
    xhr.responseType = 'blob';
    xhr.onload = function () {
        file = new Blob([xhr.response], { type : 'application/octet-stream' });
        a.href = window.URL.createObjectURL(file);
        a.download = 'someName.gif';  // Set to whatever file name you want
        // Now just click the link you created
        // Note that you may have to append the a element to the body somewhere
        // for this to work in Firefox
        a.click();
    };
    xhr.send();
    
    0 讨论(0)
  • 2020-12-06 05:17

    According to HTML element reference->[a]

    Can be used with blob: URLs and data: URLs, to make it easy for users to download content that is generated programmatically using JavaScript (e.g. a picture created using an online drawing Web app).

    If the HTTP header Content-Disposition: is present and gives a different filename than this attribute, the HTTP header has priority over this attribute.

    If this attribute is present and Content-Disposition: is set to inline, Firefox gives priority to Content-Disposition, like for the filename case, while Chrome gives priority to the download attribute.

    This attribute is only honored for links to resources with the same-origin.

    It's not from the same-origin, therefore it won't work.

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