Recently, there was a requirement of the company’s project, which was to download a “weird” format table according to the industry requirements. The back-end made a template through the table designer, and then filled in the data. The front-end obtained the base64 format data returned through the interface, and turned it into a table to provide download

The introduction ofFileSaver.js

In HTML page import, I use CDN import

<script src="http://cdn.staticfile.org/FileSaver.js/1.3.8/FileSaver.min.js"></script>
Copy the code

Convert Base64 into a downloadable file

Implement the transformation method first

function b64toFile(b64Data, filename, contentType) {
    let sliceSize = 512;
    let byteCharacters = atob(b64Data);
    let byteArrays = [];

    for (let offset = 0; offset < byteCharacters.length; offset += sliceSize) {
        let slice = byteCharacters.slice(offset, offset + sliceSize);
        let byteNumbers = new Array(slice.length);

        for (let i = 0; i < slice.length; i++) {
            byteNumbers[i] = slice.charCodeAt(i);
        }
        let byteArray = new Uint8Array(byteNumbers);
        byteArrays.push(byteArray);
    }

    let file = new File(byteArrays, filename, {type: contentType});
    return file;
}
Copy the code

Convert and download table data

// base64Data is the data obtained by the serverlet file = b64toFile(base64Data, 'test'.'application/vnd.ms-excel; charset=utf-8'); // Use FileSaver. Js to download saveAs(file,"fileName.xls");
Copy the code

Is it so easy?