SoFunction
Updated on 2025-04-05

vue background returns the format of binary stream to download files

Backend return format is binary stream for file download

Integrate in the project

Encapsulate get requests to carry tokens to receive binary streams

export function getHeader() {
    const token = getToken();
    if (token) {
        return {
            headers: {
                "Authorization": "Bearer " + token,
            }
        }
    }
    return {
        headers: {}
    }
}
 
export function getHeader() {
    const token = getToken();
    if (token) {
        return {
            headers: {
                "Authorization": "Bearer " + token,
            }
        }
    }
    return {
        headers: {}
    }
}

Use of specific documents

document:

export const dataExport2  = (vueObject, dataIdList) =>  getDataRaw(vueObject,dataExport1(dataIdList))
 
export const dataExport1 = (dataIdList)=> {
    var tmp ="";
    for (let i = 0; i <; i++) {
        tmp+= dataIdList[i]+","
    }
    tmp = (0,-1)
    var url = getUrl('image/export/' + tmp);
    return url;
}

The corresponding html file is used in specific use:

 import {
        dataExport1,
        dataExport2
    } from './TaskManageServer'
const response = await dataExport2(this, );
let blob = new Blob([], {
    //Download file type;    type: 'application/zip' 
})
// let fileName = (new Date()) + '.zip' (modify the downloaded file name)if () {
    // (blob, fileName)
    (blob)
} else {
    var link = ('a')
     = (blob)
    //  = fileName
    ()
    () //Release the memory}

You can download binary stream files.

Vue download save binary file

Method encapsulation:

/**
 * Save the binary file locally
 */
export function exportFile(file, name) {
  let url = (new Blob([file]));
  let link = ("a");
   = "none";
   = url;
  ("download", name);
  (link);
  ();
 
  (link); // Download and remove elements  (url); // Release the blob object}

Request interface

Add responseType to the request header: "arraybuffer"

export function demoApi(data) {
  return http({
    url: "/path/export",
    method: "post",
    responseType: "arraybuffer",
    data,
  });
}

Method call

demoApi(data).then(res=&gt;{
    if(==200){
        let fileName = "";
          let contentDisposition = ["content-disposition"];
          if (contentDisposition) {
            fileName = (
              ["content-disposition"].split("=")[1],
              "UTF-8"
            );//Get the file name          }
          exportFile(, fileName);
    }
})

The above is personal experience. I hope you can give you a reference and I hope you can support me more.