A BLOB is an abbreviation of a Binary Large Object.

Blobs are described in the Definitive JavaScript Guide:

A Blob is an opaque reference to, or handle for, a chunk of data.

Blobs oten represent chunks of data from an external source such as a local file, a URL, or a database.

Two characteristics of BLOB:

  • Large: Blob refers to a large block of data, such as a video file
  • Opaque: What we can do with bloBs is to set the byte length, get the MIME type, and intercept smaller bloBs.

How to get a Blob:

1. Blob supports structured Clone algorithm, so you can retrieve Blob objects from another window or thread through message events

2. Fetch the BLOB from the client database

3. Download bloBs from the network over HTTP

function getBlob(url, callback){
    let xhr = new XMLHTTPRequest();
    xhr.open("GET", url);
    xhr.responseType = "blob";
    xhr.onload = function() { callback(xhr.response); // If the downloaded blob is large, use onProgress to get the download progress xhr.send(null); }Copy the code

Through 4.BlobBuilderCreate a new BLOB object

var bb = new BlobBuilder();
bb.append('this blob contains this text and 10 big-endian 32-bit signed ints.'); // Write the string bb.append('\ 0'); Var arrayBuffer = new arrayBuffer (4*10); var dataView = new DataView(arrayBuffer);for(var i=0; i<10; i++){ dataView.setInt32(i*4, i); } bb.append(arrayBuffer); Var blob = bb.getblob ('x-optional/mime-type-here'); // Get the blob and specify the MIME typeCopy the code

5. In the client JSFileObject is a subtype of BLob. A File is Blob data with a name and lastModifiedDate attributes. Can be achieved by<input type="file">Element tag or drag interface to get File object.

<input type="file" id="ele">

const selectedFiles = document.getElementById("ele").files
The value of the // files property is an array of File objects containing zero or more files selected by the user.
for (let i = 0; i < selectedFiles.length; i++) {
    const f = selectedFiles[i]
    console.log(f.name, f.lastModifiedDate)
    console.log(f.size, f.type) // Attributes of the Blob object
}
Copy the code

You can do the following with Blob objects:

1. Create a Blob URL

A Blob URL is a reference to a Blob stored in a browser cache or on disk.

CreateObjectURL () gets the URL to the Blob data Blob :// and uses the Blob URL in the DOM and CSS just like normal urls.

Blob urls are limited by the same-origin policy and are valid only in same-origin documents.

Blob urls are not immutable and become invalid when the document that created the Blob URL is closed by the user.

Blob :// urls work in a similar way to http://URL, and browsers behave the same as HTTP requests when requesting blob:// urls. If the requested BLOB URL is no longer valid, the browser must return a 404 (Not Found) status code. When requesting bloB urls from different sources, the browser must return 403 (Not Allowed). Blob URL requests are only allowed through GET. If the request is successful, the status code 200 is returned and response.header.content-type = blob.type is returned

The following code is an image file dragged to the specified area by blob URL preview.


      
<html>
    <head>
        <script>
            // Handle browser compatibility issues
            var getBlobURL = (window.URL && URL.createObjectURL.bind(URL)) ||
                (window.webkitURL && webkitURL.createObjectURL.bind(URL)) ||
                window.createObjectURL;
            // Release the object created with createObjectURL
            var revokeBlobURL = (window.URL && URL.revokeObjectURL.bind(URL)) ||
                (window.webkitURL && webkitURL.revokeObjectURL.bind(URL)) ||
                window.revokeObjectURL;
            
            window.onload = function(){
                var droptarget = document.getElementById('droptarget');
                droptarget.ondragenter = function (e) {
                    var types = e.dataTransfer.types;
                    if(! types || (types.contains && types.contains('Files')) ||
                        (types.indexOf && types.indexOf('Files')! = =- 1)
                    ){
                        droptarget.classList.add('active');
                        return false; }}; droptarget.ondragleave =function () {
                    droptarget.classList.remove('active');
                };
                
                droptarget.ondragover = function(e) {
                    return false;
                };
                
                droptarget.ondrop = function(e) {
                    var files = e.dataTransfer.files;
                    for(var i=0; i<files.length; i++){
                        var type = files[i].type;
                        if (type.substring(0.6)! = ='image/') {
                            continue;
                        }
                        var img = document.createElement('img');
                        img.src = getBlobURL(files[i]);
                        img.onload = function () {
                            this.width = 100;
                            document.body.append(this);
                            revokeBlobURL(this.src); // Prevent memory leaks
                        }
                    }
                    droptarget.classList.remove('active');
                    return false; }}</script>
        <style>
            #droptarget {border: solid black 2px; width: 200px; height: 200px; }#droptarget.active {border: solid red 4px; }</style>
    </head>
    <body>
    <div id="droptarget">Drop Files Here</div>
    </body>
</html>
Copy the code
  1. Blob data is transferred between Windows and worker processes via postMessage()

  2. Store the BLOB in the client database

  3. Upload the BLOB to the server using the send() method of XMLHTTPRequest

5. FileReaderObject to the asynchronous interfacestringorArrayBufferExtract the contents of a BLOB object in the form of.

Because of bloBs’ large size, all apis for accessing bloBs on disk are asynchronous.

function readfile(f){
    var reader = new FileReader();
    reader.readAsText(f);
    reader.onload = function () {
        var text = reader.result;
        console.log('file content: ', text);
    }
    reader.onerror = function(e){
        console.log('Error', e); }}Copy the code
  1. throughFilesystem APIandFileWriterObject writes Blob objects to local files that are not supported by the interface browser.