哥伦布

解决a标签download不生效,只跳转新标签页需手动另存为

后端为URL时候:把server给的文件URL通过fetch转换为blob类型:变成blob:xxx

复制代码
 let url =
        "https://gimg2.baidu.com/image_search/src=http%3A%2F%2Fimg.jj20.com%2Fup%2Fallimg%2F4k%2Fs%2F02%2F2109242332225H9-0-lp.jpg&refer=http%3A%2F%2Fimg.jj20.com&app=2002&size=f9999,10000&q=a80&n=0&g=0n&fmt=auto?sec=1650945561&t=c9a7a0e4614f9d0b5510dd512aebfe27";
      fetch(url)
        .then((response) => response.blob())
        .then((res) => {
          let blob = new Blob([res]);
          // 通过URL.createObjectURL生成文件路径
          let url = window.URL.createObjectURL(blob);
          // 创建a标签
          let ele = document.createElement("a");
          ele.style.display = "none";
          // 设置href属性为文件路径,download属性可以设置文件名称
          ele.href = url;
          ele.download = "a标签dow不触发下载-单跳新页面.jpg";
          // 将a标签添加到页面并模拟点击
          document.querySelectorAll("body")[0].appendChild(ele);
          ele.click();
          // 移除a标签
          ele.remove();
        });
复制代码

响应头定义为responseType: "arraybuffer",前端自己拼接变成blob类型:变成blob:xxx

复制代码
//下载云端文件
    downloadFile(fileName) {
      this.isDownLoadProgress = true;
      axios({
        method: "get",
        url: `${process.env.VUE_APP_BASEURL}/downloadFile?roomName=${this.roomName}&fileName=${fileName}&role=教师`,
        responseType: "arraybuffer", // arraybuffer是js中提供处理二进制的接口
        onDownloadProgress: (progressEvent) => {
          if (progressEvent.lengthComputable) {
            var complete =
              ((progressEvent.loaded / progressEvent.total) * 100) | 0;
            this.downLoadValue = complete;
            if (complete >= 100) {
              this.isDownLoadProgress = false;
              this.downLoadValue = 0; // 重新置0
              this.$buefy.toast.open({
                duration: 2000,
                type: "is-success",
                message: "下载成功!",
              });
            }
          }
        },
      }).then((res) => {
        // 用返回二进制数据创建一个Blob实例
        if (!res) return;
        let blob = new Blob([res.data]); // for .xlsx files
        // 通过URL.createObjectURL生成文件路径
        let url = window.URL.createObjectURL(blob);
        // 创建a标签
        let ele = document.createElement("a");
        ele.style.display = "none";
        // 设置href属性为文件路径,download属性可以设置文件名称
        ele.href = url;
        ele.download = fileName;
        // 将a标签添加到页面并模拟点击
        document.querySelectorAll("body")[0].appendChild(ele);
        ele.click();
        // 移除a标签
        ele.remove();
      });
    },
复制代码

 

posted @   南柯Dream丶  阅读(342)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示