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

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

javascript 复制代码
window.location.href = 'url';


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

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

javascript 复制代码
window.open(url);

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

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

javascript 复制代码
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);
      });
   });
},

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

相关推荐
摘星编程17 分钟前
React Native + OpenHarmony:Stepper步进器组件
javascript·react native·react.js
●VON20 分钟前
React Native for OpenHarmony:简易计算器应用的开发与跨平台适配实践
javascript·react native·react.js
摘星编程7 小时前
OpenHarmony + RN:Placeholder文本占位
javascript·react native·react.js
a1117768 小时前
医院挂号预约系统(开源 Fastapi+vue2)
前端·vue.js·python·html5·fastapi
0思必得08 小时前
[Web自动化] Selenium处理iframe和frame
前端·爬虫·python·selenium·自动化·web自动化
计算机毕设VX:Fegn08959 小时前
计算机毕业设计|基于springboot + vue蛋糕店管理系统(源码+数据库+文档)
数据库·vue.js·spring boot·后端·课程设计
行走的陀螺仪10 小时前
uni-app + Vue3编辑页/新增页面给列表页传参
前端·vue.js·uni-app
摘星编程11 小时前
React Native + OpenHarmony:Spinner旋转加载器
javascript·react native·react.js
We་ct11 小时前
LeetCode 205. 同构字符串:解题思路+代码优化全解析
前端·算法·leetcode·typescript
2301_8127314111 小时前
CSS3笔记
前端·笔记·css3