preface
It’s not uncommon for projects to have the need to export list contents or download files. Combining various situations, I have summarized the three most common front-end methods to accept the file stream from the back end and download it. Different methods can be used for different situations.
Methods a
Usage scenarios
Get requests for the back end
The specific implementation
<a href="Back-end file download interface address"> Download file </a>Copy the code
Accept the backend file stream directly with a < A > tag
Method 2
Usage scenarios
Post requests to the back end are implemented using the native XMLHttpRequest method
The specific implementation
function request () {
const req = new XMLHttpRequest();
req.open('POST'.'< interface >'.true);
req.responseType = 'blob';
req.setRequestHeader('Content-Type'.'application/json');
req.onload = function() {
const data = req.response;
const blob = new Blob([data]);
const blobUrl = window.URL.createObjectURL(blob);
download(blobUrl) ;
};
req.send('< Request parameter: JSON string >');
};
function download(blobUrl) {
const a = document.createElement('a');
a.download = '< file name >';
a.href = blobUrl;
a.click();
}
request();
Copy the code
Methods three
Usage scenarios
The native FETCH method is implemented for back-end POST requests
The specific implementation
function request() {
fetch('< interface >', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: '< Request parameter: JSON string >',
})
.then(res => res.blob())
.then(data => {
let blobUrl = window.URL.createObjectURL(data);
download(blobUrl);
});
}
function download(blobUrl) {
const a = document.createElement('a');
a.download = '< file name >';
a.href = blobUrl;
a.click();
}
request();
Copy the code
conclusion
- If the download interface provided by the backend is
get
Type, can directly use method one, simple and convenient; Of course, if you want to use method two, three is also possible, but the feeling is a bit too far. - If the download interface provided by the backend is
post
Type, you have to use method two or method three.
How to choose between method two and method three?
- When all the interface requests in your project are based on
XMLHttpRequest
That’s what happensMethod 2More suitable, simply extend it based on the interface request utility class in your original project. - When all the interface requests in your project are based on
fetch
That’s what happensMethods threeIt’s more suitable, for example, one of the projects I’m working on right now is based onant design pro
The backend management system, which is based on the request classfetch
So I just use itMethods three, as long as in itsrequest.js
Just make a few changes in the file. - I’m talking about two native request methods here, but if your project uses a third-party request package to send a request, such as Axios, it’s a different story.