JS下载单个图片、单个视频;批量下载图片,批量下载视频

下载单张图片

import JSZip from "jszip";  
import FileSaver from "file-saver";

 

downloadIamge(imgsrc, name) {
      //下载图片地址和图片名
      let image = new Image();
      // 解决跨域 Canvas 污染问题
      image.setAttribute("crossOrigin", "anonymous");
      image.onload = function() {
        let canvas = document.createElement("canvas");
        canvas.width = image.width;
        canvas.height = image.height;
        let context = canvas.getContext("2d");
        context.drawImage(image, 0, 0, image.width, image.height);
        let url = canvas.toDataURL("image/png"); //得到图片的base64编码数据'
        let a = document.createElement("a"); // 生成一个a元素
        let event = new MouseEvent("click", {
            bubbles: true,
            cancelable: true,
            view: window
        }); // 创建一个单击事件
        a.download = name || "photo"; // 设置图片名称
        a.href = url; // 将生成的URL设置为a.href属性
        a.dispatchEvent(event); // 触发a的单击事件
      };
      image.src = imgsrc;
    },

批量下载图片,下载压缩包

batchDownloadIamge() {
      //压缩包名
      var blogTitle = "打包图片";
      var zip = new JSZip();
      var imgs = zip.folder(blogTitle);
      var baseList = [];
      // 要下载图片的url
      var arr = this.downLoadImageList;
      for (var i = 0; i < arr.length; i++) {
        let image = new Image();
        // 解决跨域 Canvas 污染问题
        image.setAttribute("crossOrigin", "anonymous");
        image.onload = function () {
          let canvas = document.createElement("canvas");
          canvas.width = image.width;
          canvas.height = image.height;
          let context = canvas.getContext("2d");
          context.drawImage(image, 0, 0, image.width, image.height);
          let url = canvas.toDataURL(); // 得到图片的base64编码数据
          canvas.toDataURL("image/png");
          baseList.push(url.substring(22)); // 去掉base64编码前的     data:image/png;base64,
          if (baseList.length === arr.length && baseList.length > 0) {
            for (let k = 0; k < baseList.length; k++) {
              imgs.file(`图片${Number(k) + 1}.png`, baseList[k], { base64: true });
            }
            zip.generateAsync({ type: "blob" }).then(function (content) {
              // see FileSaver.js
              FileSaver.saveAs(content, blogTitle + ".zip");
            });
          }
        };
        image.src = arr[i];
      }
    },

下载单个视频

downloadVideo(url, name) {
      // 使用获取到的blob对象创建的url
      const filePath = this.selectedList[0].httpAddress; // mp3的地址
      fetch(filePath).then(res => res.blob()).then(blob => {
        const a = document.createElement('a')
        document.body.appendChild(a)
        a.style.display = 'none'
        // 使用获取到的blob对象创建的url
        const url = window.URL.createObjectURL(blob)
        a.href = url
        // 指定下载的文件名
        a.download = `${name}.mp4`
        a.click()
        document.body.removeChild(a)
        // 移除blob对象的url
        window.URL.revokeObjectURL(url)
      })
    },

批量下载视频,压缩成文件包

//通过url 转为blob格式的数据
    getImgArrayBuffer(url) {
      let _this=this;
      return new Promise((resolve, reject) => {
          //通过请求获取文件blob格式
        let xmlhttp = new XMLHttpRequest();
        xmlhttp.open("GET", url, true);
        xmlhttp.responseType = "blob";
        xmlhttp.onload = function () {
          if (this.status == 200) {
            resolve(this.response);
          }else{
            reject(this.status);
          }
        }
        xmlhttp.send();
      });
    },
    // 批量下载视频
    batchDownloadVideo() {
      let _this = this;
      let zip = new JSZip();
      let cache = {};
      let promises = [];
      _this.title = '正在加载压缩文件';
      for (let item of this.selectedList) {
        const promise= _this.getImgArrayBuffer(item.httpAddress).then(data => {
          // 下载文件, 并存成ArrayBuffer对象(blob)
          zip.file(item.objectName, data, { binary: true }); // 逐个添加文件
          cache[item.objectName] = data;
        });
        promises.push(promise);
      }
 
      Promise.all(promises).then(() => {
        zip.generateAsync({ type: "blob" }).then(content => {
          _this.title = '正在压缩';
          // 生成二进制流
          FileSaver.saveAs(content, '打包视频'); // 利用file-saver保存文件  自定义文件名
          _this.title = '压缩完成';
        });
      }).catch(res=>{
        _this.$message.error('文件压缩失败');
      });
    },

 

posted @ 2023-01-31 14:56  haha-uu  阅读(1753)  评论(0编辑  收藏  举报