JavaScript blob filename without link

后端 未结 8 1964
一生所求
一生所求 2020-11-22 02:43

How do you set the name of a blob file in JavaScript when force downloading it through window.location?

function newFile(data) {
    var json = J         


        
相关标签:
8条回答
  • 2020-11-22 03:04

    Working example of a download button, to save a cat photo from an url as "cat.jpg":

    HTML:

    <button onclick="downloadUrl('https://i.imgur.com/AD3MbBi.jpg', 'cat.jpg')">Download</button>
    

    JavaScript:

    function downloadUrl(url, filename) {
      let xhr = new XMLHttpRequest();
      xhr.open("GET", url, true);
      xhr.responseType = "blob";
      xhr.onload = function(e) {
        if (this.status == 200) {
          const blob = this.response;
          const a = document.createElement("a");
          document.body.appendChild(a);
          const blobUrl = window.URL.createObjectURL(blob);
          a.href = blobUrl;
          a.download = filename;
          a.click();
          setTimeout(() => {
            window.URL.revokeObjectURL(blobUrl);
            document.body.removeChild(a);
          }, 0);
        }
      };
      xhr.send();
    }
    
    0 讨论(0)
  • 2020-11-22 03:07
    saveFileOnUserDevice = function(file){ // content: blob, name: string
            if(navigator.msSaveBlob){ // For ie and Edge
                return navigator.msSaveBlob(file.content, file.name);
            }
            else{
                let link = document.createElement('a');
                link.href = window.URL.createObjectURL(file.content);
                link.download = file.name;
                document.body.appendChild(link);
                link.dispatchEvent(new MouseEvent('click', {bubbles: true, cancelable: true, view: window}));
                link.remove();
                window.URL.revokeObjectURL(link.href);
            }
        }
    
    0 讨论(0)
提交回复
热议问题