JavaScript 下载文件
a 标签
<a href="xxx.txt" download>下载</a>动态创建a标签下载
function downloadUsingAnchorElement() {
const anchor = document.createElement('a');
anchor.href = IMG_URL;
anchor.download = FILE_NAME;
document.body.appendChild(anchor);
anchor.click();
document.body.removeChild(anchor);
}fetch下载
function downloadFile(url, fileName) {
fetch(url, {
method: "get",
mode: "no-cors",
referrerPolicy: "no-referrer",
})
.then((res) => res.blob())
.then((res) => {
const aElement = document.createElement("a");
aElement.setAttribute("download", fileName);
const href = URL.createObjectURL(res);
aElement.href = href;
aElement.setAttribute("target", "_blank");
aElement.click();
URL.revokeObjectURL(href);
});
}XMLHttpRequest
let xhr = new XMLHttpRequest();
xhr.open('GET', 'http://www.xxx.com/bbb.zip', true);
// 这部至关重要,命令xhr返回给你的时blob(二进制大对象)类型的数据
xhr.responseType = 'blob';
xhr.send()
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
const aTag = document.createElement('a')
aTag.href = URL.createObjectURL(this.response)
aTag.download = 'aaa.zip'
aTag.click()
}
}
评论
匿名评论
隐私政策
你无需删除空行,直接评论以获取最佳展示效果