Recently, the company project, there is a file export (download) function, of course, ordinary download way, such as access to a background file flow address, directly generate the corresponding file, download can, address bar can also carry some control parameters, such as? a=1&b=2), but the API interface for this project, Are adopted in the headers of the control parameters, so it can only be used in other ways.
So, after considering, through the Ajax way to request to the background of the binary stream files, using a Blob object to save the local, so that the name of the file, the suffix rule can be customized by the front-end to complete, in the following ways:
This project is based on the framework of REACT+DVA+ANTD implementation, Ajax request to use the Axios (interested students can find their own online learning, in this do not explain), then we will intercept some fragments from the project, tell the entire implementation process.
The first step is to get the data
Return Axios.get (URL, {
params:clonedata,
responsetype: ' blob ',
headers
})
The second step, processing data, the specific is to get the data, do custom processing, file name rules, and so on, here directly to get the background given the filename filename
Const DATA = yield call (filedownload, payload);
if (data.data && data.data instanceof Blob) {
//Get background filename
const realfilename=data[' headers '] [' Content-disposition '].split (' filename= ') [1];
Yield put ({type: ' SaveFile ', payload: {blob:data.data, Filename:realfilename}})
} else {
throw data
}
step Three, save the file
* SaveFile ({
payload: {blob, fileName = ' Abcdefg.xls '},
}, {call}) {
if (window.navigator.msSaveOrOpenBlob ) {
Navigator.mssaveblob (blob, fileName);
} else {
var link = document.createelement (' a ');
link.href = window. Url.createobjecturl (BLOB);
Link.download = FileName;
This is compatible with Firefox browser
document.body.appendChild (link);
var evt = document.createevent ("mouseevents");
Evt.initevent ("Click", False, false);
Link.dispatchevent (evt);
Document.body.removeChild (link);
}
,
Summary, the general implementation steps such as above, but also the whole download process key points, in this record, Masarica, Horong.