前端处理后端返回的文件流,进行文件下载

二进制流格式

 Blob格式

前言:

        需求:根据后端接口返回的文件流进行数据处理,并实现文件的下载,且下载文件为word文档.

封装下载文件接口:

最开始没带responseType:"Blob",进行文件下载后,里面的内容全部是乱码!!!

代码实现:

//下载文件
async function DownLoadFile(row) {
  let res = await DownLoadFileAPI(row.id);
  const blobURL = window.URL.createObjectURL( 
    new Blob([res.data], { type: "application/vnd.openxmlformats-officedocument.wordprocessingml.document" })
  );
  const tempLink = document.createElement("a");
  (tempLink.style.display = "none"), (tempLink.href = blobURL);
  tempLink.setAttribute("download", row.filename);
  document.body.appendChild(tempLink);
  tempLink.click();
  document.body.removeChild(tempLink);
  window.URL.revokeObjectURL(blobURL);
}

 知识点补充:

        1、new Blob(blobParts, options);

         type的常见类型

扩展名 文件类型 MIME类型
.doc Microsoft Word application/msword
.docx Microsoft Word application/vnd.openxmlformats-officedocument.wordprocessingml.document
.jpeg/.jpg JPEG 图片 image/jpeg
.mp3 MP3 音频 audio/mpeg
.pdf PDF application/pdf
.xls Microsoft Excel application/vnd.ms-excel
.xlsx Microsoft Excel application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
.zip ZIP application/zip

           查看更多:Media Types

        2、格式转化

        二进制流转blob

const blob = new Blob([BufferSource],{type:type})

        blob转base64

BlobToBase64(blob,cb){
    const fileReader = new FileReader()
    fileReader.onload = function(e){
        cb(e.target.result)
    }
    fileReader.readAsDataURL(blob)
}

猜你喜欢

转载自blog.csdn.net/m0_73334325/article/details/131685090
今日推荐