File()

The File() constructor creates a new instance of the File object.

grammar

var myFile = new File(bits, name[, options]);
Copy the code

parameter

Bits An Array containing an ArrayBuffer, ArrayBufferView, Blob, or DOMString object — or any combination of these objects. This is the utF-8 encoded file contents.

Name USVString: indicates the file name or file path.

Options Optional options object containing optional properties of the file. The options available are as follows:

  • Type: DOMString, which indicates the MIME type of the content to be placed in the file. The default value is “”.
  • LastModified: value representing the Unix timestamp in milliseconds when the file was lastModified. The default value isDate.now().

The sample

const file = new File(["my name"]."infoTxt", {
  type: "text/plain"});Copy the code

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.

Blobs don’t necessarily represent data in JavaScript’s native format. The File interface is based on Blob, inheriting Blob functionality and extending it to support files on the user’s system, while the Blob object apis are listed in the File interface.

To construct a BLOb from other non-BLOb objects and data, use the blob () constructor. To create a subset bloB of bloB data, use the slice() method. To get the Blob object corresponding to the File on the user’s File system, see the File document.

grammar

var aBlob = new Blob( array, options );
Copy the code

Returns a newly created Blob object whose content consists of the concatenation of arrays given in the arguments.

parameter

  • Array is a collection ofArrayBuffer.ArrayBufferView.Blob.DOMStringAnd so onArrayOr some mixture of similar objects, it will be put inBlob.DOMStringsIt’s going to be encoded utF-8.
  • Options is optionalBlobPropertyBagDictionary, which may specify the following two properties:
    • Type, which defaults to “”, represents the MIME type of the array content to be put into the BLOB.
    • Hamid, the default is”transparent“, used to specify how strings containing line terminator \n are written. It is one of two values:”native“, indicating that the line terminator will be changed to a newline suitable for the host operating system file system, or”transparent“, which means that the terminator saved in the BLOB is kept unchanged

attribute

Blob.size Size (in bytes) of the data contained in the read-only Blob object.

Blob.type reads only 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.

methods

Blob.slice([start[, end[, contentType]]])
Copy the code

Returns a new Blob object containing the data in the specified range in the source Blob object. This is essentially slicing up the data in the BLOB, and we need to use this method when uploading files in fragments.

Blob.stream()
Copy the code

Return a ReadableStream that can read the bloB’s contents.

Blob.text()
Copy the code

Returns a USVString in UTF-8 format that contains the full contents of the BLOB in a PROMISE.

Blob.arrayBuffer()
Copy the code

Returns an ArrayBuffer in binary format containing all the contents of the BLOB in a Promise

The sample

const data1 = "a";
const data2 = "b";
const data3 = "
      
This is a blob
"
; const data4 = { "name": "abc" }; const blob1 = new Blob([data1]); const blob2 = new Blob([data1, data2]); const blob3 = new Blob([data3]); const blob4 = new Blob([JSON.stringify(data4)]); const blob5 = new Blob([data4]); const blob6 = new Blob([data3, data4]); console.log(blob1); // Blob {size: 1, type: ""} console.log(blob2); // Blob {size: 2, type: ""} console.log(blob3); // Blob {size: 44, type: ""} console.log(blob4); // Blob {size: 14, type: ""} console.log(blob5); // Blob {size: 15, type: ""} blob5.text().then(res= > console.log(res)) // [object Object] console.log(blob6); // Blob {size: 59, type: ""} blob6.text().then(res= > console.log(res)) //
This is a blob
[object Object]
Copy the code

Size represents the number of bytes of data contained in the Blob object.

Note here that blobs created using strings are different from normal objects. Blob4 uses json.stringify to convert a data4 object to a JSON string, while Blob5 is created directly from data4, with sizes 14 and 15 respectively.

Blob4 size equals 14 is easy to understand because json.stringify (data4) results in :” {“name”:” ABC “}”, which is exactly 14 bytes (excluding the outermost quotes).

How is the size of blob5 equal to 15 calculated? In fact, when you create a Blob object from a normal object, you call the toString() method of the normal object to get the string data and then create the Blob object. So, the data stored in blob5 is “[Object object]”, which is 15 bytes (excluding the outermost quotes).

Blob URL

Blob URL is the URL of the Blob protocol. Its format is Blob :http://xxx

Blob urls can be created with url.createObjecturl (Blob). In most scenarios, we can use Blob urls just like Http urls.

Common scenarios are: as a file download address and as an image resource address.

File download address

// html
<a id="download"> download < / a >// js
const link = document.querySelector('#download')
const content = 'Blob Data'
const blob = new Blob([content], {
  type: 'text/plain' The default file type is text/plain, that is, TXT file
})
link.download = 'file' // Set the file name
link.href = URL.createObjectURL(blob)

// js automatically triggers the download
document.querySelector('#download').click()
Copy the code

Js performs the download without the need to display the A element on the page

const link = document.createElement('a')
const content = 'Blob Data'
const blob = new Blob([content], {
  type: 'text/plain' The default file type is text/plain, that is, TXT file
})
link.download = 'file' // Set the file name
link.href = URL.createObjectURL(blob)
link.click()
Copy the code

Click the Download button and the browser will download a file called File with the contents of Blob Data.

With Blob objects, we can dynamically generate files in our front-end code for the browser to download. Open the Chrome debug window and see the generated Blob URL under the Elements TAB.

Image resource address

Create a Blob URL for the image file and assign the value to the label

// html
<input type="file" accept="image/*" onchange="handleFile(this)" />
<img id="img" style="width:200px; height:200px;">

// js
function handleFile (e) {
  const file = e.target.files[0]
  const img = document.querySelector('#img')
  img.src = URL.createObjectURL(file)
  img.onload = function (e) {
    URL.revokeObjectURL(this.src) // 释放createObjectURL创建得对象
  }
}
Copy the code

In the Network TAB, you can find the request information for this Blob URL:

This request information is almost identical to what we would normally get for an image using an Http URL.

Blob urls can also be used as web addresses for other resources, such as HTML files and JSON files. To ensure that the browser can correctly parse the file type returned by the Blob URL, specify the corresponding type when creating the Blob object:

// Create a Blob URL for the HTML file
var data = "
      
This is a blob
"
; var blob = new Blob([data], {type: 'text/html'}); var blobUrl = URL.createObjectURL(blob); Copy the code

Paste the value of blobUrl, the BLOB address, into the browser address bar, as shown below

upload

FormData upload

Blob objects can be added to forms for use as upload data

const content = 'hey! ';
const blob = new Blob([content], {type: 'text/xml'});
const formdata = new FormData();	
formData.append('webmasterfile', blob);
Copy the code

Upload large files in fragments

First of all, let’s talk about sharding upload. When we upload files, the size of the files uploaded to the server will not be very large due to the limitation of the server. At this time, we need to cut the files to be uploaded and upload them to the server separately.

To do this, we need to solve two problems:

  • How do you cut it?
  • How do I know the current transmission progress?

Since File objects inherit from Blob objects, File objects also have the slice method, which can be used to slice any File.

The next step is to upload these files to the server.

Transfer-encoding Is the Encoding used to communicate with the server to determine the current shard process.

By solving these two problems, we can not only upload files in fragments, but also get the progress of uploading files.

function uploadFile(file) {
  const chunkSize = 1024 * 1024; // Each piece is 1M in size
  const totalSize = file.size;
  const chunkQuantity = Math.ceil(totalSize / chunkSize); // Total number of fragments
  let offset = 0; / / the offset

  const reader = new FileReader();
  reader.onload = function(e) {
    const xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    xhr.overrideMineType("application/octet-stream");
    
    xhr.onreadstatechange = function() {
      if(xhr.readyState === 4 && xhr.status ===200) {
        ++offset;
        if(offset === chunkQuantity) {
          alert("Upload completed");
        } else if(offset === chunckQuantity - 1) {
          blob = file.slice(offset * chunkSize, totalSize);
          reader.readAsBinaryString(blob);
        } else {
          blob = file.slice(offset * chunkSize, (offset+1) * chunckSize); reader.readAsBinaryString(blob); }}else {
        alert("Upload error"); }}if(xhr.sendAsBinary) {
      xhr.sendAsBinary(e.target.result);
    } else{ xhr.send(e.target.result); }}const blob = file.slice(0, chunkSize);
  reader.readAsBinaryString(blob);
}
Copy the code

This code can be further enriched by displaying the current upload progress, using multiple XMLHttpRequest objects to upload objects in parallel (passing the location parameters of the shard data to the server), and so on.

download

const imgBlob = fetchedImgData(); // Set responseType to blob and fetchedImgData to asynchronous. The actual service needs to be processed asynchronously
const blob = new Blob([imgBlob], {type: 'image/png' }); // Pass in an appropriate MIME type
const url = URL.createObjectURL(blob);
// produces a URL string like blob: d3958f5C-0777-0845-9dcF-2CB28783acaf
// You can use it like a normal URL, such as img.src.
Copy the code

Extract data from bloBS

One way to read content from a Blob is to use FileReader. The following code reads the contents of the Blob as an array of types:

const reader = new FileReader();
reader.readAsArrayBuffer(blob);
reader.addEventListener("load ".function(readRes) {
   // readres.target. result converts to the blob of the arrayBuffer
});
Copy the code

Blobs can be read as strings or data urls by other methods using FileReader.

Another way to read the contents of a Blob is to use a Response object. The following code reads the contents of the Blob as text:

var text = await new Response(blob).text();
Copy the code