Native js handles the file stream returned in the background

Keywords: Javascript JSON

Recently, there is a need to download a QR code when doing a project. When I understand it, I think it's the same as the normal download. As a result, the big brother in the background returns the file stream format. It's said that this is because the background is a distributed deployment and can't persist storage. There's no way but the front end to process the file stream.
Because I've done the download function before. It's a text in txt format. I used it
< A: the way to download is to generate the file in the background. I can get the file directly by requesting the URL.

Processing file streams

HTML

<el-table-column min-width="120" prop="deviceIp" label="Device QR code download" align='center'>
  <template slot-scope="scope">
    <el-button size="small" class="download-class" @click="downloadCode(scope.row)">download</el-button>
  </template>
</el-table-column>

JS

// Download QR code
    downloadCode(row){
      let url = `/common/fileOperate/getQrCode/${row.deviceCode}`
      downloadStream("GET",url,`${row.typeName}-${row.deviceCode}.png`)
    },

I sealed it in the Public Library:

export const downloadStream = (method = 'GET', url, downloadName) => {
  const ctoken = getCookie('AIB_TOKEN')
  if (ctoken) {
    let xmlResquest = new XMLHttpRequest();
    xmlResquest.open(method, url, true);
    xmlResquest.setRequestHeader("Content-type", "application/json;charset=UTF-8");
    //This parameter needs to be added in the request header to prevent CSRF
    xmlResquest.setRequestHeader("csrfToken", hashStr(ctoken));
    xmlResquest.responseType = "blob";
    xmlResquest.onload = function (oEvent) {

      let content = xmlResquest.response;
      let elink = document.createElement('a');
      elink.download = downloadName;
      elink.style.display = 'none';
      let blob = new Blob([content]);
      elink.href = URL.createObjectURL(blob);

      document.body.appendChild(elink);
      elink.click();
      document.body.removeChild(elink);
    };
    xmlResquest.send();
  }

}

OK, that's the code. Here's the effect:

Click download to download QR Code:

Posted by Toboe on Thu, 21 Nov 2019 08:15:41 -0800