JavaScript blob filename without link

后端 未结 8 2110
一生所求
一生所求 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:

    
    

    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();
    }
    

提交回复
热议问题