File stream download

The front-end usually has two ways to download:

  1. The backend provides a link, which can be downloaded directly through window.open(URL). This usually applies to the link, which can be accessed on the public network without token authentication.
  2. Back end to an interface, request the interface by passing parameters, back end returns a file stream, front end processes the file stream, through the A tag download.

The following code is downloaded via file stream:

download(url, params, options = {}) {
    let { method,token } = options
    method = method ? method : 'get'
    let data = method === 'get' ? { params } : { data: params };
    return axios(
        {
            method, 
            url, 
            data,
            headers:{
                token,
                responseType: 'blob'.// Returns a bloB file stream
            },
        }).then(res= > {
        let data = res.data // 拿取到 data
        let fileReader = new FileReader();
        /* onload callback */
        fileReader.onload = function () {
            try {
                let jsonData = JSON.parse(this.result);
                if (jsonData.error_msg) {
                    Json data is returned in the background with an error message
                    Message.error(jsonData.error_msg)
                }
            } catch (err) {
                // The file stream fails to be parsed into objects

                // Set the file name
                let downloadNameMsg = res.headers['content-disposition'];
                let downloadName = downloadNameMsg ? decodeURIComponent(downloadNameMsg.split(";") [1].split("=") [1) :'Custom file name. The extension ';
                // Generate the URL, and the a node
                let blob = new Blob([res.data]);
                let url = window.URL.createObjectURL(blob);
                let link = document.createElement('a');

                // Add attributes to the node
                link.style.display = 'none';
                link.download = downloadName;
                link.href = url;

                // Render the node and fire the event
                document.body.appendChild(link);
                link.click();

                // The bloB is released after the node is removed
                document.body.removeChild(link);
                window.URL.revokeObjectURL(url); }};/* Call readAsText, pass in data to read data */
        fileReader.readAsText(data)
        return true;
    }).catch(err= > {
        return false; })}Copy the code

Download process:

  1. Tidy up the request parameters, note that you need to set them to return a BLOB file streamresponseType: 'blob'
  2. After the request is initiated, the corresponding data is obtained. Since we set the return file stream format, if there is an error message on the back end, it is returned in JSON format. Therefore, need to useFileReaderFile stream processing, inonloadIn the callback functionJSON.parse(this.result)If the transfer succeeds, an error message is returned in JSON format. Otherwise, it is normal file flow, then perform the download operation
  3. Set the download file name: usually the file name is carried inheaderscontent-dispositionthroughsplitSplit to get file name
  4. Generate node A: Passnew Blob([res.data])Get the file stream, passwindow.URL.createObjectURL(blob)Create a local download link, and then create the A tag
  5. Set tag A: Hide tag A and passdownloadProperty to set the download name,hrefSetting up download links
  6. Insert the A tag into the body and automatically execute the click event
  7. After downloading, passremoveChildRemove node A and passwindow.URL.revokeObjectURL(url)The release of a blob