Vue axios implements download files and responseType: blob considerations

Need to use axios and js-file-download components

npm install js-file-download --save
npm install axios --save
import fileDownload from 'fileDownload'; // 引入fileDownload
import axios from 'axios'; // 引入axios 

axios({
	method: 'get',
    url: 'xxxxxxx',
    responseType: 'blob'
}).then(res => {
    if(res.status == 200){
      // res.headers['content-disposition'].substring(20)表示从响应头中获取文件名
      fileDownload(res.data,res.headers['content-disposition'].substring(20));
    }else { // 下载文件失败,解析json格式信息
      let that = this;
      var fileReader = new FileReader();
      fileReader.readAsText(res.data); // 按字节读取文件内容,结果为文件的二进制串
      fileReader.onload = ()=>{
          that.$notify.error(fileReader.result);
      }
    } 
})

Notes: responseType: blob indicates that the response type returned by the server is a binary stream, which is generally used in scenarios such as file and video downloading. Under normal circumstances, the backend returns binary data. When the backend server makes an error, it often returns error information in the form of json, such as {"code":500,"msg":"Unknown exception"}. Because the blob type is set, axios will force the data to be converted to blob, resulting in json format responses that cannot be parsed normally and need to be processed using a FileReader object. FileReader is an asynchronous file reading mechanism. FileReader provides the following methods, which you can choose according to your needs.

  • readAsArrayBuffer(file): Read the file content by bytes, and the result is represented by an ArrayBuffer object

  • readAsBinaryString(file): Read the file content by bytes, the result is the binary string of the file

  • readAsDataURL(file): Read the file content, and the result is expressed in the string form of data:url

  • readAsText(file,encoding): Read the file content by characters, and the result is expressed in string form

Guess you like

Origin blog.csdn.net/weixin_46205984/article/details/132563160
Recommended