Recently a file download, then set responseType: Blob way, what is it Blob, MDN official explanation: Blob
object represents an immutable, file-like object original data. JavaScript is not necessarily the data in its native format (Blob represented https://developer.mozilla.org/zh-CN/docs/Web/API/Blob ).
axios request as follows:
axios.get({ url: 'xxxxxx', method: 'get', data:{}, responseType: 'blob' }).then(res => {
downLoadBlobFile (res.data, fileName, mimeType); // This method will be given later
});
This way I will be able to download files normally, but after a few test data, found open after download some file, as shown:
View the interface, the interface does return to normal original error object that contains the error code and error messages, but because it is a blob data type, can not be captured, so it is still being treated as a file downloaded.
API returns:
js attempt to get the returned data:
Blob data is acquired stream, we need to convert it to the job json format, as follows:
Data = the let res.data; the let FileReader = new new the FileReader (); fileReader.onload = function () { the try { the let jsonData = the JSON.parse ( the this .Result); // indicates a regular target data back conversion fails IF ( jsonData.code) { Alert ( 'fail ...' ); } } the catch (ERR) { // parse into the object fails, the file is a normal flow Alert ( 'Success ...' );
downLoadBlobFile(res.data, fileName, mimeType);
}
};
fileReader.readAsText(data)
Jiang Zi can get to a normal json data, you want of town friends ~
Method attachment downLoadBlobFile:
export const downLoadBlobFile = (data: Blob, fileName?: string, type?: string) => { //type为Mime类型 let name = fileName || new Date().toLocaleDateString(); let typeStr = type ? type : 'application/vnd.ms-excel'; if (window.navigator.msSaveOrOpenBlob) { //兼容性处理 const blob = new Blob([data], { type: typeStr }); navigator.msSaveBlob(blob, name); } else { const excelBlob = new Blob([data], { type: typeStr }); let oa = document.createElement('a'); oa.href = URL.createObjectURL(excelBlob); oa.download = name; document.body.appendChild(oa); oa.click(); } };
Note that the parameter type is a MIME type, MIME common document types can refer to the MDN: https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Complete_list_of_MIME_types
Reference documents: https://blog.csdn.net/dongguan_123/article/details/100183284