preface

  • To do so, you need to download an Excel spreadsheet.
  • Basically the back end renders an Excel format binary, the interface returns an ArrayBuff(an array binary object) type file, and the front end makes it available for the user to download.
  • The back end cannot directly provide the download link. With the protection of token, we need to do some extra processing in the front end.

Take a look at the url.createObjecturl (Object) method and the BLOB object

createObjectURL

objectURL = URL.createObjectURL(object);

  • The File object, Blob object, or MediaSource object used to create the URL.

blob

  • What is a BLOB object?
    • A Blob (Binary Large Object) Object represents a piece of Binary data and provides a series of interfaces for manipulation. Other apis for manipulating binary data, such as File objects, are built on top of Blob objects, inheriting their properties and methods.

var aBlob = new Blob( array, options );

  • An array is an array made up of objects such as ArrayBuffer, ArrayBufferView, Blob, DOMString, etc., or a mixture of similar objects that will be put into the Blob. DOMStrings will be encoded to UTF-8.

  • Options is an optional BlobPropertyBag dictionary that may specify the following two properties:

Type, which defaults to “”, represents the MIME type of the array content to be put into the BLOB. Hamed, whose default value is “transparent”, specifies how the string containing the line end \n is written. It is one of two values: “native”, which means that the line terminator is changed to a newline suitable for the host operating system file system, or “transparent”, which means that the end character saved in the BLOb is left unchanged

var debug = {hello: "world"};
var blob = new Blob([JSON.stringify(debug, null.2)] and {type : 'application/json'});
  
// Get a blob
Copy the code

DownloadFile function

  • The ArrayBuffer object returned by the interface

  • Overview of main Interfaces

Let’s start writing the main code

  • html
<button onclick="DownloadFile (api.getexcel (),{excel_name: 'Data form'})">Click on the download</button>

Copy the code
  • js
 / * * *@param {*} ApiUrl // API address *@param {*} Params // Configuration item *@param {*} BlobType // File type, you can pass in a reasonable type * with the backend@param {*} FileSuffix // fileSuffix, the specific suffix depends on the requirements */

 function downloadFile(apiUrl, params = { excel_name: 'data' }, blobType = 'application/ynd.ms-excel; charset=UTF-8',excelTypeSuffix:string = 'xls') { 

    if(! apiUrl) {console.error('please input API URL! ');
        
        return;
    }

    // This example uses axios, apiUrl for the related interface provided by the back end
    return axios
        .get(apiUrl, {
            params,
            responseType: 'arraybuffer'
        })
        .then(
            resp= > {
                // Wrap the resP returned from the back end as a Blob type
                let localHref = window.URL.createObjectURL(
                    new Blob([resp], { type: blobType })
                );
                
                // Create an A tag to download the file
                let ele = document.createElement('a');

                ele.href = localHref;

                The // download attribute determines the name of the file to download
                ele.download = `${params.excel_name}.${excelTypeSuffix}`;

                document.querySelectorAll('body') [0].appendChild(ele);

                ele.click();

                // Remove the a tag to free memory
                setTimeout(() = > {
                    ele.remove();
                }, 1000);
            },
            err= > {
                console.error(err);
            }
        )
        .finally(() = > {
            console.log('end')}); }Copy the code
  • The download file is shown below

How to handle file stream interface return error?

  • Main issues: Since the interface returns the ArrayBuffer format, we need to check whether the returned data has byteLength. If so, we use the following aspects to convert the data to a normal JSON format: Error.error_message is displayed as normal
let data = response.data
 // Handle responseType: 'arrayBuffer' error
if (data && data.byteLength) {
    var enc = new TextDecoder('utf-8');

    data = JSON.parse(enc.decode(new Uint8Array(response.data))) || {};
}
Copy the code
  • Refer to MDN for details
  • Developer.mozilla.org/zh-CN/docs/…

reference

  • MDN File type
  • [MDN how to use file](developer.mozilla.org/en-US/docs/…

)

  • Stackoverflow.com/questions/3…
  • Developer.mozilla.org/zh-CN/docs/…
  • Developer.mozilla.org/zh-CN/docs/…