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

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

相关推荐
2501_9444241230 分钟前
Flutter for OpenHarmony游戏集合App实战之连连看路径连线
android·开发语言·前端·javascript·flutter·游戏·php
search78 小时前
前端设计:CRG 3--CDC error
前端
治金的blog8 小时前
vben-admin和vite,ant-design-vue的结合的联系
前端·vscode
利刃大大9 小时前
【Vue】Vue2 和 Vue3 的区别
前端·javascript·vue.js
Lhuu(重开版9 小时前
JS:正则表达式和作用域
开发语言·javascript·正则表达式
荔枝一杯酸牛奶10 小时前
HTML 表单与表格布局实战:两个经典作业案例详解
前端·html
Charlie_lll10 小时前
学习Three.js–纹理贴图(Texture)
前端·three.js
yuguo.im11 小时前
我开源了一个 GrapesJS 插件
前端·javascript·开源·grapesjs
安且惜11 小时前
带弹窗的页面--以表格形式展示
前端·javascript·vue.js
摘星编程12 小时前
用React Native开发OpenHarmony应用:NFC读取标签数据
javascript·react native·react.js