1. Obtain the back-end binary file flow

The first thing you need to do is make sure that the back end of the call returns the binary file properly

The return looks like this. (Sometimes there are cross-domain issues at the back end, as explained below.)

2. Stream the returned binary file into a downloadable file address using the Blob object.

A Blob object represents an immutable, raw data-like file object. See the MDN

  1. Set at request timereponseTypeforblob, specifying that the data type of the response is BLOb.
axios.post(url,param,{ responseType: 'blob'})
Copy the code
  1. Process the returned results
const fileDownload = (res, filename) = > {
  let blob = new Blob([res.data]); // Pass the returned data through the Blob constructor to create a Blob object
  if ('msSaveOrOpenBlob' in navigator) {
    window.navigator.msSaveOrOpenBlob(blob, filename); // For browsers
  } else {
    const elink = document.createElement('a'); // Create a tag
    elink.download = filename; 
    elink.style.display = 'none';
    // Create a URL that points to the blob, where you can click to download the file from the root
    elink.href = URL.createObjectURL(blob); 
    document.body.appendChild(elink);
    elink.click();
    URL.revokeObjectURL(elink.href); // Remove the link
    document.body.removeChild(elink); // Remove the a tag}}Copy the code
  1. The complete code
axios.post(url,param,{responseType: 'blob'})
      .then((res: any) = > {
        if (res.status === 200) {
          fileDownload(res, 'Test file.xlsx'); }});Copy the code

Note that the file name can be obtained from headers[” Content-disposition “] on the backend. You need to negotiate with the backend to Expose the header to you (not what you can see in the console, but the header with Content-disposition and accesss-Control-expose-headers listed)

3. The download request is cross-domain

  1. The problem
Request cross domain, back end and I bicker, say other request why not cross domain… He’s already set it up across domains. (My cross-domain is back-end processing, front-end does not do proxy)
  1. Brian dozen face

His use of Response.reset () across domains was reset, causing global cross-domain invalidation. For detailed explanation, please refer to this elder brother to solve the problem of cross-domain file transfer failure in front and back end separation. That that go punch him in the face.