<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>Blob 文件下载示例</title>
</head>
<body>
<button id="downloadBtn">文件下载</button>
<script>
const download = (fileName, blob) => {
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = fileName;
link.click();
link.remove();
URL.revokeObjectURL(link.href);
};
const downloadBtn = document.querySelector('#downloadBtn');
downloadBtn.addEventListener('click', (event) => {
/* // 下载文本文件
const fileName = 'blob.txt';
const myBlob = new Blob(['一文彻底掌握 Blob Web API'], { type: 'text/plain' });
download(fileName, myBlob);
*/
// 下载网络连接图片
const myRequest = new Request('http://n.sinaimg.cn/sinakd20200630ac/338/w640h498/20200630/10ef-ivrxcex7820615.jpg');
fetch(myRequest)
.then((response) => {
return response.blob();
})
.then((myBlob) => {
download('1.jpg', myBlob);
});
});
</script>
</body>
</html>
网友评论