vue如何使用文件流进行下载(new Blob)

2022-09-22 11:42:01

目录vue使用文件流进行下载(newBlob)封装方法vue下载文件流完整前后端代码vue使用文件流进行下载(newBlob)封装方法functiongetExel(url,params,i...

目录
vue使用文件流进行下载(new Blob)
封装方法
vue下载文件流完整前后端代码

vue使用文件流进行下载(new Blob)

封装方法

function getExel(url, params, index) {+
 return new Promise(function(resolve, reject) {
  let data = {
   method: "GET",
   url:url,
   headers: {
    'token': gettoken("token")
   },
   responseType: 'arraybuffer'
  }
  resolve(axIOS(data));
 })
}

注意:responseType应设置为:'arraybuffer'

发送请求($Api已经挂载在了vue对象上,所以可以这么使用)

this.$Api.getExel("/goodsCheckService/v1/planMaterial/export?idList="+idArray)
     .then(response => {
       let a = document.createElement('a');

       //ArrayBuffer 转为 Blob
       let blob = new Blob([response.data], {type: "application/vnd.ms-excel"});
      
       let objectUrl = URL.createObjectURL(blob);
       a.setAttribute("href",objectUrl);
       a.setAttribute("download", '计划单电子表格.xls');
       a.click();
});

vue下载文件流完整前后端代码

使用Vue时,我们前端如何处理后端返回的文件流

首先后端返回流,这里我把流的动作拿出来了,我很多地方要用

  /**
  * 下载单个文件
  *
  * @param docId
  */
  @GetMapping("/download/{docId}")
  public void download(@PathVariable("docId") String docId,
            HttpServletResponse response) {
    outWrite(response, docId);
  }
 
 /**
  * 输出文件流
  * @param response
  * @param docId
  */
  private void outWrite(HttpServletResponse response, String docId) {
    ServletOutputStream out = null;
    try {
      out = response.getOutputStream();
      // 禁止图像缓存。
      response.setHeader("Pragma", "no-cache");
      response.setHeader("Cache-Control", "no-cache");
      response.setDateHeader("Expires", 0);
      byte[] bytes = docService.downloadFileSingle(docId);
      if (bytes != null) {
        MagicMatch match = Magic.getMagicMatch(bytes);
        String mimeType = match.getMimeType();
        response.setContentType(mimeType);
        response.addHeader("Content-Length", String.valueOf(bytes.length));
        out.write(bytes);
      }
      out.flush();
    } catch (Exception e) {
      UnitedLo编程gger.error(e);
    } finally {
      IOUtils.closeQuietly(out);
    }
  }

前端这里我引入了一个组件 js-file-download

npm install js-file-download --save

然后在Vue文件中添加进来

import fileDownload from "js-file-download";
 // 文档操作列对应事件
  async handleCommand(item, data) {
   switch (item.key) {
    case "download":
     var res = await this.download(data);
     return fileDownload(res, data.name);
    ...
    default:
   }
   // 刷新当前层级的列表
   const folder = this.getLastFolderPath();
   this.listClick(folder.folderId, folder.name);
  },
  // 下载
  async download(row) {
   if (this.isFolder(row.type)) {
    return FolderAPI.download(row.id);
   } else {
    return DocAPI.download(row.id);
   }
  },

docAPI js 注意需要设置responseType

/**
* 下载单个文件
* @param {*} id
*/
const download = (id) => {
 return request({
  url: _DataAPI.download + id,
  method: "GET",
  responseType: 'blob'
 });
};

这样即可成功下载 

以上为个人经验,希望能给大家一个参考,也希望大家多多支持我们。