JavaScript blob filename without link

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

    Same principle as the solutions above. But I had issues with Firefox 52.0 (32 bit) where large files (>40 MBytes) are truncated at random positions. Re-scheduling the call of revokeObjectUrl() fixes this issue.

    function saveFile(blob, filename) {
      if (window.navigator.msSaveOrOpenBlob) {
        window.navigator.msSaveOrOpenBlob(blob, filename);
      } else {
        const a = document.createElement('a');
        document.body.appendChild(a);
        const url = window.URL.createObjectURL(blob);
        a.href = url;
        a.download = filename;
        a.click();
        setTimeout(() => {
          window.URL.revokeObjectURL(url);
          document.body.removeChild(a);
        }, 0)
      }
    }
    

    jsfiddle example

提交回复
热议问题