javascript - 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);
});
}
解决方案
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 并创建一个可下载的图像
推荐阅读
- sql - 以行而不是单行显示 SQL 结果
- asp.net-core - DisableRequestSizeLimit 和 RequestFormLimits 在服务器上不起作用
- r - 在最右列和最底行创建具有平均值的热图
- node.js - 无法连接到 selenium chrome 独立驱动程序
- angular - Firebase 身份验证仍然会在控制台中引发错误,即使我发现了它
- reactjs - 无法使用反应上下文值
- google-bigquery - 如何在 Big Query 中将表从一个数据集移动到另一个数据集
- django - HttpResponseRedirect 有额外的路径并失败
- vba - 检测最近Xs中是否修改了组合框
- angular - 在组件之间共享文件数据