VUE导出excel文件 -blob方法返回文件流并下载问题

请求接口返回如下图所示:

先设置请求类型:

responseType: 'blob'


responseType: 'blob'

 exportLineStatisticsInfo(id)
        .then((resp) => {
          console.log(resp);
          let blob = new Blob([resp], { type: "application/vnd.ms-excel" });
          let objectUrl = URL.createObjectURL(blob);
          window.open(objectUrl, "_blank");
        })
        .catch((error) => {
          this.$message.error(error);
        });

返回后记得设置类型type: "application/vnd.ms-excel"

不知道类型可以直接console.log打印查看类型:

最后通过链接打开  直接下载

PS: 当直接使用window.open 时,遇到浏览器无法预览的文件会直接下载(如exel表格等)但遇到浏览器能预览的文件(如图片、pdf等)会打开新页面而不会下载,如果想直接下载该文件需用如下写法:


.then((resp) => {
     if(resp.data.size>0){
          const _res = resp.data;
          const fileName = resp.headers["content-disposition"].split("=")[1];//下载文件全名(未转码)
          let blob = new Blob([_res], {type: 'application/pdf'});
          let downloadElement = document.createElement("a");
          let href = window.URL.createObjectURL(blob); //创建下载的链接
          downloadElement.href = href;
          downloadElement.download = decodeURIComponent(fileName).split(".")[0]; //下载后文件名(转码并去掉全名后的.pdf)
          document.body.appendChild(downloadElement);
          downloadElement.click(); //点击下载
          document.body.removeChild(downloadElement); //下载完成移除元素
          window.URL.revokeObjectURL(href); //释放掉blob对象
        }else{
          this.$message.error("暂无故障报告");
        }
      })
      .catch((error) => {
        this.$message.error(error);
      });  

没有 固定格式文件的可以写一个方法来输出对应文件下载格式:

const typeDic = {
    docx: 'application/msword',
    doc: 'application/msword',
    bin: 'application/octet-stream',
    exe: 'application/octet-stream',
    so: 'application/octet-stream',
    dll: 'application/octet-stream',
    pdf: 'application/pdf',
    ai: 'application/postscript',
    xls: 'application/vnd.ms-excel',
    xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
    ppt: 'application/vnd.ms-powerpoint',
    dir: 'application/x-director',
    js: 'application/x-javascript',
    swf: 'application/x-shockwave-flash',
    xhtml: 'application/xhtml+xml',
    xht: 'application/xhtml+xml',
    zip: 'application/zip',
    mid: 'audio/midi',
    midi: 'audio/midi',
    mp3: 'audio/mpeg',
    rm: 'audio/x-pn-realaudio',
    rpm: 'audio/x-pn-realaudio-plugin',
    wav: 'audio/x-wav',
    bmp: 'image/bmp',
    gif: 'image/gif',
    jpeg: 'image/jpeg',
    jpg: 'image/jpeg',
    png: 'image/png',
    css: 'text/css',
    html: 'text/html',
    htm: 'text/html',
    txt: 'text/plain',
    xsl: 'text/xml',
    xml: 'text/xml',
    mpeg: 'video/mpeg',
    mpg: 'video/mpeg',
    avi: 'video/x-msvideo',
    movie: 'video/x-sgi-movie'
};
//根据文件后缀名来映射Blob Type
export const getFileTypeFn = (fileType) => {
    return typeDic[fileType]
}

猜你喜欢

转载自blog.csdn.net/zhufan2333/article/details/125988311