The paper

For security reasons, the front-end cannot write files directly. But in the actual business requirements, it is inevitable to encounter a variety of files download, preview. If the server downloads files as streams to the front-end, the front-end usually converts the streams to objectURL and uses the Download attribute of the A tag to download files. In this case, the return format of the server message is json instead of stream. In this case, although the front-end can export the file normally, the file content is the message returned by the server, which is not properly disposed. In this case, it would be good to have a method to read the stream. This article gives a brief overview of the way the front end reads binary streams.

Binary file download

Normal binary download: First, the response-type of the request header needs to be set to BLOB, and second, the following methods can be called when a response message is received.

function download(blob) {
    // Create a blob link
    let url = URL.createObjectURL(blob)
    let a = document.createElement('a')
    a.setAttribute('download', url)
    a.href=ur;
    a.style.display = 'none'
    document.body.appendChild(a)
    a.click()
    document.body.removeChild(a)
    // Each time url.createObjecturl is called, a new URL object is created, and the reference to this object is kept in the browser's memory
    // This part of memory is freed only when the document is destroyed
    // For performance reasons, it is best to free this portion of memory after the URL is used
    URL.revokeObjectURL(url)
}
Copy the code

Binary file reading

If the response type returned by the server is Content-Type =application/json, we still parse and process it in the way of binary stream, which will cause problems in the exported file content. For example, in Excel, the content is the message responded by the server. Therefore, We need to do a pre-intercept when processing the server response content.

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

Blob content can be read in two main ways, FileReader and Response.

FileReader

ReadAsArrayBuffer, readAsBinaryString, readAsDataURL, readdAsText The FileReader reading methods are as follows:

  var reader = new FileReader()
  reader.addEventListener('loadend'.function (e) {
    // Output string {hello: world}
    console.log(e.target.result)
  })
  reader.readAsText(blob)
Copy the code

Response

Response is an interface to the Fetch API that renders a Response to a request for data. Browser compatibility is less than FileReader and supports Chrome 42+ and FireFox 39+.

The Response to instantiate

let myResponse = new Response(body, init)
Copy the code
  1. body
    • Blob
    • BufferSource
    • FormData
    • URLSearchParams
    • USVString
  2. init
    • status
    • statusText
    • headers

Response implements the body interface, so when instantiating Response, you can call body.blob (), body.formData(), body.json(), and body.text() to serialize the return value, which is a Promise. The specific implementation method is as follows:

  var blobReader = new Response(blob).json()
  blobReader.then(res= > {
      console.log(res)
  })
Copy the code

summary

With the method of parsing the return value from the server, we can determine the content-Type of the return value from the server when downloading the file. If the return value is not a BLOB, we can do some customization.

The resources

  • Blob
  • FileReader
  • Response