The front end processes the blob or json format returned by the back end

background

There is an interface to upload excel, and the backend performs batch processing

If any data fails, return a failedexcel文件流

If all succeed, return ajson

problem analysis

responseTypeIf it is an interface for downloading files, it can only be set to one of the formats when the front-end requests

Then by default, the return in another case cannot be read normally

key point

  1. result.data.typeThe real return type can be obtained in axios , even if the request content-typeisblob
  2. If it is , you can get the json data jsonbyresult.data.text().then((text) => {})
    // 通过这种方式取出返回的errorMsg
    blob.text().then((text) => {
          
          
      ElMessage.error(JSON.parse(text).debugMsg);
    });
    

fully realized

const download = async (url: string, data: any): Promise<any> => {
    
    
  const loadingInstance = ElLoading.service();
  const result = await axios.post(
    BASE_URL + url,
    deleteObjectFalsityValueAttribute(data),
    {
    
    
      withCredentials: true,
      responseType: "blob",
      timeout: 4 * 60 * 1000,
    }
  );
  // 如果返回不是文件类型,需要提示
  if (result.data.type === "application/json") {
    
    
    const blob = result.data;
    // 通过这种方式取出返回的errorMsg
    blob.text().then((text) => {
    
    
      ElMessage.error(JSON.parse(text).debugMsg);
    });
    loadingInstance.close();
    return false;
  }
  const blobData: any[] = [];
  blobData.push(result.data);
  const download_url = window.URL.createObjectURL(
    new Blob(blobData, {
    
     type: result.data.type })
  );
  const a = document.createElement("a");
  a.href = download_url;
  let fileName = result.headers["content-disposition"].substr(20);
  // 如果是zip类型需要解码后端base64加密的
  if (result.data.type === "application/octet-stream") {
    
    
    fileName = decodeBase64(fileName);
  }
  a.download = decodeURI(fileName).replace("=utf-8''", "");
  document.body.appendChild(a);
  a.click();
  a.remove();
  loadingInstance.close();
  return true;
};

Guess you like

Origin blog.csdn.net/qq_43382853/article/details/130268491