Note: In development, we always encounter some problems of downloading back file streams, in this case, we can use Blob objects to solve this problem

To use Blob objects, we need to be clear:

1. What is the Blob object?

It is an immutable, raw data – like file object. Its data can be read in text or binary format, and can be converted to a ReadableStream for data manipulation. Is a binary large object and a container that can store binary files.

2. What properties and methods does it have?

Blob objects have size and type properties and a slice() method;

Size: indicates the size of the Blob in bytes. The binary data of a Blob object can be read using the FileReader interface. If the Blob object has no number of bytes, the size attribute is 0.

Type: represents a string indicating the MIME type of the data contained in the Blob object. If the type is unknown, the value is an empty string.

Slice () : you can slice a Blob object and return a new Blob object.


constNewBlob * blob. Slice (start, end, contentType);// The start parameter represents the subscript in the Blob, indicating the starting position of the first byte that will be copied into the new Blob

// End represents a subscript of the Blob, and the byte corresponding to the subscript -1 will be the last byte to be copied into the new Blob.

// contentType gives the new Blob a new document type. This will set its type attribute to the value passed in. Its default value is an empty string.

Copy the code

Now that we know what a Blob is, we can use it in our projects.

Used in projects

ResponseType: ‘blob’
    return request('interface', {
      method: 'POST'.responseType: 'blob'.data: {... params, }, });Copy the code
The returned file stream is processed

Response is the obtained file stream

(response: any) => {
    // Create bloB objects
    const blob = window.URL.createObjectURL(
        new Blob([response]),
        );
    // Create a link
    const aLink=document.createElement('a');
    // Set to hide a link
    aLink.style.display='none';
    // Give the created bloB to a.href
    aLink.href=blob;
    // Set the name of the file to be downloaded
    aLink.download='The name of the file to download. The type ';
    // Add a link to the body
    document.body.appendChild(aLink);
    // Click the a link
    aLink.click();
    // Remember to delete the link created when you are done
    document.body.removeChild(aLink);
    }
Copy the code