0
点赞
收藏
分享

微信扫一扫

vue 下载图片/视频到浏览器

窗外路过了谁 10小时前 阅读 1

方法1:直接在当前页面打开图片或者视频

window.location.href = 'url';


//借用a标签实现同样效果
const link = document.createElement('a')
link.href = 'url' // 文件地址
link.click();

方法2:新开一个窗口打开图片或视频

window.open(url);

方法3:下载到浏览器的下载文件夹中,需要手动打开:

代码中有注释,可支持多种文件类型

downLoadFunc(imgSrc, imgName) {
  if (!imgSrc) return;
  fetch(imgSrc, {
     method: "get",
     headers: {
     Authorization: localStorage.getItem("token"),
    },
  }).then(function (response) {
     response.arrayBuffer().then((res) => {
        let type = "image/*";
        // 常见资源类型
        // 1.excel: type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
        // 2.图片: type = "image/*"
        // 3.视频: type = "video/*"
        // 4.音频: type = "audio/*"
        // 5.pdf: type = "application/pdf;charset-UTF-8"
        let blob = new Blob([res], { type: type });
        let objectUrl = URL.createObjectURL(blob);
        let link = document.createElement("a");
        link.style.display = "none";
        link.href = objectUrl;
        link.setAttribute("download", imgName);
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
      });
   });
},

暂时总结,如有问题,欢迎留言一起讨论~

举报

相关推荐

0 条评论