JS——blob

1. [HTML5] Blob object

(1) Write in front : This section mainly introduces the properties and functions of Blob objects, and introduces the application scenarios of blob objects through demos.

Blob object: All along, JS has no better way to directly deal with binary. The existence of blobs allows us to directly manipulate binary data through js.

"A blob object is a file-like object that contains read-only raw data. The data in the blob object does not necessarily have to be in its native form in JavaScript. The file interface is based on blobs, inherits the functions of blobs, and extends support for user computers Local files on

The Blob object can be seen as a container for storing binary data, and in addition, the MIME type of the binary data can be set through blobs.

(2) Create a blob

Method 1: Through the constructor


var blob = new Blob(dataArr:Array<any>,opt:{type:string});

dataArr : array, contains the data to be added to the blob object, the data can be any number of ArrayBuffer, ArrayBufferView, blob or DOMString objects

opt : object, used to set the attributes of the Blob object (such as MIME type)

MIME: Each URL represents a resource object, and when we request a web page, it seems that only one URI (uniform resource identifier) ​​is requested. In fact, this web page may contain multiple URIs, such as the URI of an image resource And the URI of the video resource. At this time, some browsers may open multiple threads to request the URI in order to speed up the access speed. In other words, every URI sends a request message. When our browser wants to display or process these resources, we do not know what type of data the response is. In order to distinguish these resource types, we need to use MIME. HTTP will add a MIME type data format tag to each object transmitted through the web. After reading the corresponding information, the browser will call the corresponding program to deal with it, and any result we want.

The first: create a blob object filled with DOMString objects

image

The second kind: create a Blob object filled with ArrayBuffer object

image

The third type: create a Blob object filled with ArrayBufferView object (ArrayBufferView can be created based on ArrayBuffer, the return value is an array-like. As follows, create an 8-byte ArrayBuffer, create a 2-byte array element on each "view")

image

Method 2: Through Blob.slice ()


This method returns a new Blob object containing the data in the specified range of the original blob object

Blob.slice(start:number,end:number,contentType:string)

start: start index, default is 0

end: ending index (excluding end)

contentType: the MIME type of the new blob, the default is an empty string

image

Method 3: Via canvas.toBlob ()


var canvas = document.getElementById("canvas");

canvas.toBlob(function(blob){

console.log(blob);

});

2. Application scenarios

As mentioned earlier, the file interface inherits blob, inherits the function of blob and extends it, so we can use File object like Blob

Multipart upload


Through the Blob.slice method, large files can be fragmented, and each file fragment can be submitted to the background in a round-robin manner, and the file can be uploaded in slices.

The logic for uploading fragments is as follows:

Get the File object of the file to be uploaded , and split the file according to the chunk (each piece size)

Each file is uploaded in a round-robin manner through the post method, where the querystring stitched in the url is used to describe the information of the currently uploaded file; the post body stores the binary data fragments to be uploaded

The interface returns offset every time, used to perform the next upload

The following is a simple implementation of multipart upload:

 

initUpload();//初始化上传functioninitUpload(){

    var chunk = 100 * 1024;  //每片大小    var input = document.getElementById("file");    //input file    input.onchange = function(e){

        var file = this.files[0];

        var query = {};

        var chunks = [];

        if (!!file) {

            var start = 0;

            //文件分片            for (var i = 0; i < Math.ceil(file.size / chunk); i++) {

                var end = start + chunk;

                chunks[i] = file.slice(start , end);

                start = end;

            }

            // 采用post方法上传文件            // url query上拼接以下参数,用于记录上传偏移            // post body中存放本次要上传的二进制数据            query = {

                fileSize: file.size,

                dataSize: chunk,

                nextOffset: 0            }

            upload(chunks, query, successPerUpload);

        }

    }

}// 执行上传functionupload(chunks, query, cb){

    var queryStr = Object.getOwnPropertyNames(query).map(key=> {

        return key + "=" + query[key];

    }).join("&");

    var xhr = new XMLHttpRequest();

    xhr.open("POST", "http://xxxx/opload?" + queryStr);

    xhr.overrideMimeType("application/octet-stream");

    //获取post body中二进制数据    var index = Math.floor(query.nextOffset / query.dataSize);

    getFileBinary(chunks[index], function(binary){

        if (xhr.sendAsBinary) {

            xhr.sendAsBinary(binary);

        } else {

            xhr.send(binary);

        }

    });

    xhr.onreadystatechange = function(e){

        if (xhr.readyState === 4) {

            if (xhr.status === 200) {

                var resp = JSON.parse(xhr.responseText);

                // 接口返回nextoffset                // resp = {                //    isFinish:false,                //    offset:100*1024                // }                if (typeof cb === "function") {

                    cb.call(this, resp, chunks, query)

                }

            }

        }

    }

}// 每片上传成功后执行functionsuccessPerUpload(resp, chunks, query){

    if (resp.isFinish === true) {

        alert("上传成功");

    } else {

        //未上传完毕        query.offset = resp.offset;

        upload(chunks, query, successPerUpload);

    }

}// 获取文件二进制数据functiongetFileBinary(file, cb){

    var reader = new FileReader();

    reader.readAsArrayBuffer(file);

    reader.onload = function(e){

        if (typeof cb === "function") {

            cb.call(this, this.result);

        }

    }

}


 

Published 51 original articles · 19 praises · 60,000+ views

Guess you like

Origin blog.csdn.net/qq_40999917/article/details/105296644