js下载blob文件

header设置
if (responseType == 'blob') {
headerJosn['content-disposition'] = "attachment;filename=total.xls"
headerJosn['content-type'] = 'application/x-download;charset=utf-8';
}
if (responseType == 'upload') {
headerJosn['content-type'] = 'multipart/form-data';
}
this.$httpRequest.get(url, data, 'blob').then(res => {
try {
//这里res是返回的blob对象
  let blob = new Blob([res], {
   type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8'
  }); //application/vnd.openxmlformats-officedocument.spreadsheetml.sheet这里表示xlsx类型
  // 下载类型大全 https://blog.csdn.net/yin_you_yu/article/details/116261304
  let downloadElement = document.createElement('a');
  let href = window.URL.createObjectURL(blob); //创建下载的链接
  downloadElement.href = href;
  let time = (new Date()).valueOf();
  downloadElement.download = '下载名称' + time + '.csv'; //下载后文件名
  document.body.appendChild(downloadElement);
  downloadElement.click(); //点击下载
  document.body.removeChild(downloadElement); //下载完成移除元素
  window.URL.revokeObjectURL(href); //释放掉blob对象
} catch (e) {}
})
posted @ 2022-03-06 11:41  吃饭七分饱  阅读(993)  评论(0编辑  收藏  举报