美文网首页
2020-07-01 前端实现图片下载

2020-07-01 前端实现图片下载

作者: FConfidence | 来源:发表于2020-07-01 00:44 被阅读0次
<!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>

相关文章

网友评论

      本文标题:2020-07-01 前端实现图片下载

      本文链接:https://www.haomeiwen.com/subject/syeqqktx.html