vue in axios (async / await) for binary stream file Download

Demand: the back-end interface to download excel / docx files (various files anyway), no back-end file address, return a binary stream file

First, the interface address

// 文件下载
export function downloadFlie (fileId, fileName) {
  return request({
    url:  '/v1/downLoad/' + fileId + '/' + fileName,
    method: 'GET',
    responseType: 'arraybuffer', //blob
    headers: {
      'Content-Type': 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    }
  })
}

Note:
responseType must arraybufferorblob

Request header Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet

Second, the use

1, do not change the file name

async download(){
  let blob = new Blob([await downloadFlie(this.fileId, this. fileName)], { type: "application/[vnd.ms-excel;charset=utf-8](vnd.ms-excel;charset=utf-8)" });
 // 通过 URL.createObjectURL(Blob对象), 可以把 Blob对象 转换成一个链接地址,该地址可以直接用在某些 DOM 的 src 或者 href 上
  let objectUrl = URL.createObjectURL(blob);   //
  window.location.href = objectUrl;   //
 }

2, modify the file name

async download(){
   let fileName = '哈哈哈.docx'
   let blob = new Blob([await downloadFlie(this.fileId, fileName)], { type: "application/[vnd.ms-excel;charset=utf-8](vnd.ms-excel;charset=utf-8)" });
   // 通过 URL.createObjectURL(Blob对象), 可以把 Blob对象 转换成一个链接地址,该地址可以直接用在某些 DOM 的 src 或者 href 上
   const link = document.createElement('a'); //创建a标签
   link.href = window.URL.createObjectURL(blob);  //创建下载的链接
   link.download = fileName; //文件名
   link.click(); //点击下载
   window.URL.revokeObjectURL(link.href); 
//window.URL.revokeObjectUR()下载链接)释放blob对象
   link.remove(); //将a标签移除
 }

Reproduced in: https: //www.jianshu.com/p/ecb76afd71d7

Guess you like

Origin blog.csdn.net/weixin_34362875/article/details/91099580