Writing in the front

In the actual development process, users often encounter the need to download or export a file. The traditional way is to store or generate a file in the back end to provide the download function, which has the advantage of permission control and convenient secondary data processing, but has the disadvantage of additional request initiation, increasing the pressure on the server and slow download speed. However, with the release of HTML5 standard, my big front-end has been completely independent of file download and export ~

Download the file using the DOWNLOAD attribute of the A TAB

The Download property instructs the browser to download the URL rather than navigate to it, prompting the user to save it as a local file. If the property has a value, this value will be used as a prepopulated file name during the download save (the user can still change the file name if desired). This property has no limit on the allowed values, but/and \ are converted to underscores. Most file systems limit punctuation in file names, so browsers will adjust the suggested file names accordingly.

<a download="File name" href="File Address">Download the test</a>
Copy the code

Note that:

  1. Download only works with same-origin urls, but blob: urls and data: urls can be used.
  2. If the HTTP headerContent-DispositionAttribute assigns a filename different from this attribute, and the HTTP header attribute takes precedence over this attribute.
  3. If HTTP header propertyContent-DispositionIs set to inline, i.eContent-Disposition='inline', then Firefox prioritizes HTTP headersContent-DispositionDownload the properties.

Generate Data URLs and download the file

Data urls are urls prefixed with the Data: protocol that allow content creators to embed small files into documents. It consists of four parts: a prefix (data:), a MIME type indicating the data type, an optional Base64 tag if it is not text, and the data itself.

Data :[<mediatype>][;base64],<data> Mediatype is a string of MIME type. For example, "image/ JPEG "indicates a JPEG image file. If omitted, the default is text/plain; Charset =US-ASCII If the data is text, you can embed the text directly if it's binary, you can base64 encode the data and then embed it.Copy the code

Examples of code for exporting files:

// Export the Json file
exportJson(){
    const downloadData = {
        name:"April".ager:"18".hobby:"Learning"
    };
    let dataStr = "data:text/json; charset=utf-8," + encodeURIComponent(JSON.stringify(downloadData));
    let downloadAnchorNode = document.createElement('a')
    downloadAnchorNode.setAttribute("href", dataStr);
    downloadAnchorNode.setAttribute("download"."Filenames. Json")
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
},
Copy the code

Generate the BLOB: URL and download the file

The Blob() constructor returns a new Blob object. The content of a BLOB consists of a concatenation of values given in an array of parameters.

let aBlob = new Blob( array, options );
Copy the code

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:

  1. typeThe default value is “”, which represents the MIME type of the array content to be put into the BLOB.
  2. endings, the default value is"transparent"To specify the inclusion line terminator\nHow the string is written. It is one of two values:"native", indicating that the end-of-line character is changed to a newline suitable for the host operating system file system, or"transparent", which means that the terminator saved in the BLOB is kept unchanged.

The url.createObjecturl () static method creates a DOMString with a URL representing the object given in the argument. The lifecycle of this URL and the Document binding in the window that created it. This new URL object represents the specified File object or Blob object.

objectURL = URL.createObjectURL(object);
Copy the code

Examples of code for exporting files:

exportJson() {
    const downloadData = {
        name: "April".ager: "18".hobby: "Learning"
    };
                
    let blob = new Blob(
        [JSON.stringify(downloadData, null.2)] and {type: 'application/json'});
    let url = URL.createObjectURL(blob);
    let downloadAnchorNode = document.createElement('a')
    downloadAnchorNode.setAttribute("href", url);
    downloadAnchorNode.setAttribute("download"."Filenames. Json")
    downloadAnchorNode.click();
    downloadAnchorNode.remove();
 }
Copy the code

Click to download image

Although browsers currently support the function of saving pictures to local (right-click > Save pictures as), the actual development will involve the function of downloading pictures in batches and saving Canvas drawing. With the above knowledge, my front-end can also easily achieve it. The code is as follows:

 <button @click="downloadImg">Download the pictures</button>
Copy the code
// Get the blob object of the image by SRC
getImageBlob(url, cb) {
    let xhr = new XMLHttpRequest();
    xhr.open("get", url, true);
    xhr.responseType = "blob";
    xhr.onload = function () {
        if (this.status == 200) {
            cb(this.response); }}; xhr.send(); },// Click to download the image
downloadImg(){
    let reader = new FileReader();
    this.getImageBlob('https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-assets/v3/static/img/simplify-logo.3e3c253.svg~tplv-t2oaga2asx-image .image'.function(blob){
        // Take a look at the resulting string from the downloaded content
        reader.readAsDataURL(blob);
        // Generate a URL object for the download
        let url = URL.createObjectURL(blob);
        // Create an A label and click on it to download it. Same with batch download
        let downloadAnchorNode = document.createElement('a')
        downloadAnchorNode.setAttribute("href", url);
        downloadAnchorNode.setAttribute("download"."Download picture") downloadAnchorNode.click(); downloadAnchorNode.remove(); })},Copy the code

Download the form

SheetJS jS-XLSX is an easy-to-use excel library that requires only PURE JS to read and export Excel files in a wide range of formats, including XLS, XLSX, ODS and more. The XLSX format is used as an example throughout this article. Official Github: github.com/SheetJS/js-…

// Test data
staff: [
    {name: "April".job: "programmer".age: "18".hobby: "study"},
    {name: "Shawn".job: "student".age: "8".hobby: "study"},
    {name: "Leo".job: "teacher".age: "28".hobby: "play"},
    {name: "Todd".job: "programmer".age: "19".hobby: "sleep"},
    {name: "Scoot".job: "cook".age: "38".hobby: "paintting"},]Copy the code

Install XLSX

npm install xlsx --save
Copy the code
import XLSX from 'xlsx';
Copy the code
auto_width(ws, data) {
    /*set worksheet max width per col*/
    const colWidth = data.map(row= > row.map(val= > {
        /*if null/undefined*/
        if (val == null) {
            return {'wch': 10};
        }
        /*if chinese*/
        else if (val.toString().charCodeAt(0) > 255) {
            return {'wch': val.toString().length * 2};
        } else {
            return {'wch': val.toString().length}; }}))/*start in the first row*/
    let result = colWidth[0];
    for (let i = 1; i < colWidth.length; i++) {
        for (let j = 0; j < colWidth[i].length; j++) {
            if (result[j]['wch'] < colWidth[i][j]['wch']) {
                result[j]['wch'] = colWidth[i][j]['wch'];
            }
        }
    }
    ws['! cols'] = result;
},
json_to_array(key, jsonData) {
    return jsonData.map(v= > key.map(j= > {
        return v[j]
    }));
},
export_array_to_excel({key, data, title, filename, autoWidth}) {
    const wb = XLSX.utils.book_new();
    const arr = this.json_to_array(key, data);
    arr.unshift(title);
    const ws = XLSX.utils.aoa_to_sheet(arr);
    if (autoWidth) {
        this.auto_width(ws, arr);
    }
    XLSX.utils.book_append_sheet(wb, ws, filename);
    XLSX.writeFile(wb, filename + '.xlsx');
},
exportExcel() {
    let staff = this.staff;
    const params = {
        title: ['name'.'work'.'age'.'hobby'].key: ['name'.'job'.'age'.'hobby'].data: staff,
        autoWidth: true.filename: 'File name'
    }
    this.export_array_to_excel(params)
},
Copy the code

Read data from uploaded files

The only way to read Blob data is with FileReader. The FileReader object allows a Web application to asynchronously read the contents of a File (or raw data buffer) stored on the user’s computer, using a File or Blob object to specify which File or data to read.

The File object can be a FileList object returned by the user after selecting a File on an element, or it can be generated by a drag-and-drop operation DataTransfer object, which can also be returned from mozGetAsFile() on an HTMLCanvasElement.

Contains 5 methods:

  1. Filereader.abort () aborts the read operation. On return, the readyState property is DONE.

  2. FileReader. ReadAsArrayBuffer () reads the specified the contents of the Blob, once done, the result attribute will be read the file is saved in the ArrayBuffer data objects.

  3. FileReader. ReadAsBinaryString () reads the specified the contents of the Blob. Once done, the Result property contains the raw binary data for the file being read.

  4. Filereader.readasdataurl () begins reading the contents of the specified Blob. Once complete, the result property contains a string in data: URL format to represent the contents of the file being read.

  5. Filereader.readastext () begins reading the contents of the specified Blob. Once complete, the Result property contains a string representing the contents of the file being read.

Code example of reading an uploaded file as a string

handleUpload(blob) {
    Create a new FileReader
    const reader = new FileReader()
    // Read the file
    reader.readAsText(blob, "UTF-8")
    // After reading the file, I will come back here
    reader.onload = function (e) {
        // Read the contents of the file
        const fileString = e.target.result
        // The file contents can then be processed
        const myData = JSON.parse(fileString);
        console.log(myData) // Print what is read}},Copy the code

Code example of reading an uploaded file as a string in URL format

handleUpload(file) {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = function (e) {
        const urlStr = reader.result
        console.log(urlStr)
    }
}
Copy the code

Read and upload Excel files

Also recommended is the JS-XLSX from SheetJS

import XLSX from 'xlsx';
Copy the code
handleUpload(file) {
    let that = this;
    var reader = new FileReader();
    reader.readAsBinaryString(file);
    reader.onload = function (evt) {
      var data = evt.target.result;
      var workbook = XLSX.read(data, {
        type: 'binary'
      }) // Read the entire Excel table object in binary stream mode
    }
    reader.onload = function (evt) {
      // This function is called after reading, and the contents of the file are stored in result
      try {
        var data = evt.target.result,
          workbook = XLSX.read(data, {
            type: 'binary'
          }), // Read the entire Excel table object in binary stream mode
          buildings = []; // Store the obtained data
        var fromTo = ' ';
        // read through each table
        for (var sheet in workbook.Sheets) {
          if (workbook.Sheets.hasOwnProperty(sheet)) {
            fromTo = workbook.Sheets[sheet]['! ref']; buildings = buildings.concat(XLSX.utils.sheet_to_json(workbook.Sheets[sheet])); }}console.log(buildings) // File contents
      } catch (e) {
        console.log('Incorrect file type', e);
        return; }}return false;
},
Copy the code