A get method
<a href="后端文件下载接口地址"> Download the file </a>
The direct use of a file tab to accept the back-end flow
Method two post
use scenario
for the rear end of the post request
using XMLHttpRequest native methods implemented
Implementation
function request () { const req = new XMLHttpRequest(); req.open('POST', '<接口地址>', true); req.responseType = 'blob'; req.setRequestHeader('Content-Type', 'application/json'); req.onload = function() { const data = req.response; const a = document.createElement('a'); const blob = new Blob([data]); const blobUrl = window.URL.createObjectURL(blob); download(blobUrl) ; }; req.send ( '<request parameters: json string>' ); }; function downloads (blobUrl) { const A = document.createElement ( 'A' ); a.style.display = 'none' ; a.download = "<filename>" ; a.href = blobUrl; a.click (); document.body.removeChild (A); } Request ();
Method three
usage scenarios
for the rear end of the post request
using native fetch implemented method
Implementation
function request() { fetch('<接口地址>', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: '<请求参数:json字符串>', }) .then(res => res.blob()) .then(data => { let blobUrl = window.URL.createObjectURL(data); download(blobUrl); }); } function download(blobUrl) { const a = document.createElement('a'); a.style.display = 'none'; a.download = '<文件名>'; a.href = blobUrl; a.click(); document.body.removeChild(a); } request();
Method Two Method three and how to choose?
When your project is based on the interface request full realization of XMLHttpRequest, then second method would be more suitable, as long as the original project based on your request interface tools to be expanded on the line.
When your project request all interfaces, then the method based on three fetch achieve even more suitable, for example, I now do a project that is based on ant design pro backstage management system, which is based inside the fetch request class of , so I'll just use the method three, as long as the minor modifications in its request.js file on the line.
I discussed here are two ways to request native, if you project referenced third-party request packet to send the request, such as axios and the like, it would be another matter.