preface
ResponseType: “blob” responseType: “blob” responseType: “blob” responseType: “blob” responseType: “blob” responseType: “blob”
The specific implementation
The project carries out secondary encapsulation of the request based on AXIOS. The code is as follows:
export function sendGet(url: string, params: object = {}, options: object = {}) :Promise<any> {
return new Promise(async (resolve, reject) => {
try {
options["params"] = params;
let res = await http.get(url, options);
if(res) { resolve(res); }}catch(e) { reject(e); }}); }Copy the code
The specific interface for downloading execution is:
// Interface encapsulation
import {
`sendGet`
} from "Method Encapsulation address";
//
export const loadTemplate = data= >
sendGet('Specific service interface address', data, {
responseType: "blob"
});
Copy the code
If the responseType: “blob” is not set when the interface API is defined, the downloaded file is corrupt.
Triggered by an event on a page:
loadTemplate().then(res= > {
console.log(res);
createExcelFile(
res,
"Template definition name"."application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
});
Copy the code
The res returned from loadTemplate is the stream of binary files returned from the back end. The file is then downloaded using createExcelFile.
File download Method To facilitate expansion, a file type field is added, which can be passed as a parameter to facilitate the download of various files.
/** * File download *@param {} res- Binary file stream *@param {string} fileName- Download file name definition *@param {string} type- Type of file to download */
export default (res, fileName, type = "application/vnd.ms-excel") = > {const blob = new Blob([res], { type: type }); //type Indicates that the default file type is XLSX
const downloadElement = document.createElement("a");
const href = window.URL.createObjectURL(blob); // Create a download link
downloadElement.href = href;
downloadElement.download = fileName; // Download the file name
document.body.appendChild(downloadElement);
downloadElement.click(); // Click download
document.body.removeChild(downloadElement); // Remove the element after downloading
window.URL.revokeObjectURL(href);
};
Copy the code
However, there will be a problem, if the backend student does not return the binary file stream to you, it will report an error, of course, if the convention is good, it will not do so, but in order to avoid such situation, I also made the corresponding processing, a new judgment method.
// Remember that response is passed in here, not response.data as requested
function judgeErrorByResponseType(response) {
return new Promise((resolve, reject) = > {
if (response.headers['content-type'].includes('json')) {
// The data obtained here is the blob
const { data } = response
const reader = new FileReader()
reader.onload = () = > {
const { result } = reader
const errorInfos = JSON.parse(result)
const { msg } = errorInfos
reject(new Error(msg))
}
reader.onerror = err= > {
reject(err)
}
reader.readAsText(data)
} else {
resolve(response)
}
})
}
Copy the code
This method is also written with a requirement in the background that it returns the exact content-Type. If it is a JSON data format error, you must return Application/JSON.
The judgeErrorByResponseType above is simple and requires a decision before downloading.
loadTemplate().then(res= > {
console.log(res);
const response = judgeErrorByResponseType(res)
createExcelFile(
response,
"Template definition name"."application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
);
});
Copy the code
subsequent
Mockjs affects axios to download the responseType property, but I’m not using it here
I hope this article can help more front-end students who encounter the same problem, so that we can avoid detours ~~~