在这里插入图片描述
需求:
多选之后点击批量下载,下载不同类型的文件,有各种格式的图片,有word文档,有pdf等。
我用的iview 框架的table组件。
直接上代码

// script 中的代码
export const downloadFile = url => {
  const iframe = document.createElement("iframe");
  iframe.style.display = "none";
  iframe.style.height = 0;
  iframe.src = url;
  document.body.appendChild(iframe);

  setTimeout(() => {
    iframe.remove();
  }, 5 * 60 * 1000);
};
// methods中的代码
bulkDownload() {
      var that = this;
      console.log(that.AllDownList);
      if (that.AllDownList.length == 0) {
        this.$Message.warning("请选择要下载的课件");
      } else {
        for (let i = 0; i < this.AllDownList.length; i++) {Ï
          // let name = this.AllDownList[i].courseName;
          let url =
            axios.defaults.baseURL +
            "/file/get?fileId=" +
            this.AllDownList[i].fileName;
            //判断数据中是什么类型的文件。courseCategory是项目自己定义的文件类型
          if (this.AllDownList[i].courseCategory == "image") {
            this.downloadIamge(url, this.AllDownList[i].courseName);
          } else {
            downloadFile(url);
          }
        }
		// 取消多选
        this.$refs.selection.selectAll(false);
        
      }
    },
	 downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      var image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function() {
        var canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        var context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        var url = canvas.toDataURL("image/png"); //得到图片的base64编码数据

        var a = document.createElement("a"); // 生成一个a元素
        var event = new MouseEvent("click"); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
    }


Logo

前往低代码交流专区

更多推荐