vue 文件下载

64 阅读1分钟

1.下载单个文件

 singleUpload(url) {
      const link = document.createElement('a');
      // 将链接地址url转成blob地址,
      fetch(url).then(res => res.blob()).then(blob => {
        link.href = URL.createObjectURL(blob)
        // 下载文件的名称
        link.download = row.url.substr(url.lastIndexOf('/') + 1);
        document.body.appendChild(link)
        link.click()
        //在资源下载完成后 清除 占用的缓存资源
        window.URL.revokeObjectURL(link.href);
        document.body.removeChild(link);
      });
    },

2.下载多个文件并压缩
安装:npm i jszip
npm i file-saver

import JSZip from 'jszip'
import FileSaver from 'file-saver'

//fileList:[{filepath:xx,filename:xx}]
//初始化zip函数
export function initZip(fileList) {
  var blogTitle = `全部`; // 下载后压缩包的名称
  var zip = new JSZip();
  var promises = [];
  let cache = {};
  for (let item of fileList) {
    // item.feilePath为文件链接地址
    // item.fileName为文件名称
    if (item.filepath) {
      const promise = getImgArrayBuffer(item.filepath).then((data) => {
        // 下载文件, 并存成ArrayBuffer对象(blob)
        zip.file(item.filename, data, { binary: true }); // 逐个添加文件
        cache[item.filename] = data;
      });
      promises.push(promise);
    } else {
      // feilePath地址不存在时提示
      Message.error(`附件${item} 地址错误,下载失败`);
    }
  }
  Promise.all(promises)
    .then(() => {
      zip.generateAsync({ type: "blob" }).then((content) => {
        // 生成二进制流
        FileSaver.saveAs(content, blogTitle); // 利用file-saver保存文件  blogTitle:自定义文件名
      });
    })
    .catch((res) => {
      Message.error("文件压缩失败");
    });
}
//文件以流的形式获取(参数url为文件链接地址)
export function getImgArrayBuffer(url) {
  return new Promise((resolve, reject) => {
    //通过请求获取文件blob格式
    let xmlhttp = new XMLHttpRequest();
    xmlhttp.open("GET",url, true);
    xmlhttp.responseType = "blob";
    xmlhttp.onload = function () {
      if (xmlhttp.status == 200) {
        resolve(xmlhttp.response);
      } else {
        reject(xmlhttp.response);
      }
    };
    xmlhttp.send();
  });
}