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);
      });
   });
},

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

相关推荐
再学一点就睡14 小时前
前端网络实战手册:15个高频工作场景全解析
前端·网络协议
C_心欲无痕15 小时前
有限状态机在前端中的应用
前端·状态模式
C_心欲无痕15 小时前
前端基于 IntersectionObserver 更流畅的懒加载实现
前端
candyTong15 小时前
深入解析:AI 智能体(Agent)是如何解决问题的?
前端·agent·ai编程
柳杉15 小时前
建议收藏 | 2026年AI工具封神榜:从Sora到混元3D,生产力彻底爆发
前端·人工智能·后端
weixin_4624462315 小时前
使用 Puppeteer 设置 Cookies 并实现自动化分页操作:前端实战教程
运维·前端·自动化
CheungChunChiu15 小时前
Linux 内核动态打印机制详解
android·linux·服务器·前端·ubuntu
Irene199116 小时前
Vue 官方推荐:kebab-case(短横线命名法)
javascript·vue.js
GIS之路16 小时前
GDAL 创建矢量图层的两种方式
前端
2501_9481953417 小时前
RN for OpenHarmony英雄联盟助手App实战:符文配置实现
javascript·react native·react.js