首页 > 解决方案 > javascript从路径下载文件

问题描述

下面是我用来下载文件的示例,但它只在下一个选项卡中打开文件。它不下载文件。

function download(items) {
 
  items.forEach(function (item, index) {
   // console.log(item);
    var anchor = document.createElement('a');
    anchor.href = item.url;
    anchor.target = '_blank';
    anchor.download = item.name;
    anchor.innerHTML ='download';
    setTimeout(function () {
    //  console.log(anchor);
      anchor.click();      
    }, index * 100);
  });
}

标签: javascripthtmllaravelfiledownload

解决方案


fetch("https://upload.wikimedia.org/wikipedia/commons/a/a3/June_odd-eyed-cat.jpg")
    .then(response => response.blob())
    .then(blob => {

        const blobURL = URL.createObjectURL(blob);
        const a = document.createElement("a");
        a.href = blobURL;
        a.innerHTML = "download"
        a.setAttribute('download', 'true')
        document.body.appendChild(a);

    })

下载属性仅适用于同源 URL

此 API 调用需要一个 URL 并创建一个可下载的图像


推荐阅读