“This article has participated in the call for good writing activities, click to view: the back end, the big front end double track submission, 20,000 yuan prize pool waiting for you to challenge!”
Last week, I wrote two articles on saving resource downloads, one on saving resource files under the browser Blob size limit and the other on saving resource files under the browser memory limit (more than 2G). If you’re interested, check it out. This series is an extension of the previous two articles, extending all possible types of personal study notes through Blob/File.
Portal: Look at resource file download save, how robust? The front end breaks through browser Blob and RAM size limits to save files in SAO gameplay!
An overview of
Here is a picture of the conversion of binary data related data types. Let’s follow the process.
This article writes:readBlob
forArrayBuffer
orData URL
.
- Blob
A Blob object represents an immutable, raw data-like file object. Its data can be read in text or binary format, or converted to [ReadableStream] for data manipulation.
- ArrayBuffer
The ArrayBuffer object is used to represent a generic, fixed-length buffer of raw binary data. It is an array of bytes, often referred to as a “byte array” in other languages. You can’t manipulate the contents of the ArrayBuffer directly, but rather through [type Array Object] or [DataView] objects, which represent the data in the buffer in specific formats and read and write the contents of the buffer in those formats.
- DataURLs
Data URLs, URLs prefixed with the Data: protocol, allow content creators to embed small files into documents. Data URLs are made up of four parts: a prefix (Data :), a MIME type that indicates the Data type, an optional Base64 tag if it’s not text, and the Data itself:
data:[<mediatype>][;base64],<data>
Copy the code
With the basic type concepts behind it, let’s look at how to read bloBs. Of course, there is no way to read Blob data directly in Js, so some transformation is required. Otherwise, this article is meaningless.
implementation
1. Blob.arrayBuffer
With blob.ArrayBuffer () it returns a Promise object containing a binary arrayBuffer of all the Blob’s contents.
var debug = {hello: "world"};
var blob = new Blob([JSON.stringify(debug, null, 2)], {type : 'application/json'});
// 异步获取
blob.arrayBuffer().then(arraybuffer=>console.log(arraybuffer))
Copy the code
2. With the help of 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 the File or data to read. It exposes several apis that can read the contents of the Blob in the following manner.
- ReadAsArrayBuffer: After reading, the Result property holds the ArrayBuffer data object
- ReadAsBinaryString: After reading, the result property holds the raw binary data
- ReadAsDataURL: When read, the result property contains a Base64 string in data:URL format
- ReadAsText () : When read, the result property contains a string
var reader = new FileReader(); AddEventListener (" loadEnd ", function() {// reader.result contains typed array blobs}); reader.readAsArrayBuffer(blob);Copy the code
3. Response constructor
The Response interface of the Fetch API renders the Response data for a request. You can create a Response object using the Response.response () constructor.
let myResponse = new Response(body, init);
Copy the code
The body argument is optional, can be null, or one of the following:
- Blob
- BufferSource
- FormData
- ReadableStream
- URLSearchParams
- USVString
So we can use this constructor to read the Blob, of course, if the type is correct:
var text = await (new Response(blob)).text();
var arrayBuffer = await (new Response(blob)).arrayBuffer();
var json = await (new Response(blob)).json();
Copy the code
4. To expand ReadableStream
The ReadableStream interface in the stream operations API renders a readable binary stream operation. The Fetch API provides a concrete ReadableStream object via the Body property of Response.
Fetch ("https://www.example.org/").then((response) => {// Create a reader and lock the stream on it. Once locked, no other readers can read it until it is freed. const reader = response.body.getReader(); Const stream = new ReadableStream({start(controller) {function push() {// "done" is a Boolean, Uint8Array reader.read().then(({done, value}) => { If (done) {// Tell the browser that the data is finished sending controller.close(); return; } // get the data and send it to the browser controller.enqueue(value) via controller; push(); }); }; push(); }}); return new Response(stream, { headers: { "Content-Type": "text/html" } }); });Copy the code
conclusion
These are several ways to read bloBs, and ArrayBuffer and TypeArray are planned for the next article. Finally, for the read stream related advice, take a look at the portal: the front end itself breaks the browser’s Blob and RAM size limits to save files in a cool way! There is actual combat.
Finally, the customer leave a thumbs up! Take you five points to review JS treasure ~