更改Blob文件名

时间:2019-04-30 22:31:38

标签: javascript html

我正在使用https://stackoverflow.com/a/49500465/10241621中的代码从链接下载文件。确实可以,但是我不知道如何创建自定义文件名。

duplicates

1 个答案:

答案 0 :(得分:1)

新文件名是函数downloadResource(url, filename)的第二个参数

function forceDownload(blob, filename) {
  var a = document.createElement('a');
  a.download = filename;
  a.href = blob;
  // For Firefox https://stackoverflow.com/a/32226068
  document.body.appendChild(a);
  a.click();
  a.remove();
}

// Current blob size limit is around 500MB for browsers
function downloadResource(url, filename) {
  if (!filename) filename = url.split('\\').pop().split('/').pop();
  fetch(url, {
      headers: new Headers({
        'Origin': location.origin
      }),
      mode: 'cors'
    })
    .then(response => response.blob())
    .then(blob => {
      let blobUrl = window.URL.createObjectURL(blob);
      forceDownload(blobUrl, filename);
    })
    .catch(e => console.error(e));
}

downloadResource('https://giant.gfycat.com/RemoteBlandBlackrussianterrier.webm', 'NewName');

相关问题