Complete step uploading with BLOB

BLOB BLOB, BINARY LARGE Object Abbreviation, binary type large object, representing the original data

in the computer, blob is often a database Use the field type of binary files to store binaries.

Basic usage

Blob object refers to byte sequences, And has a size property, which is the total number of bytes in the byte sequence, and a TYPE property, which is a small-written ASCII encoded string representing the media type byte sequence.
Size: Returns the size of the byte sequence with bytes. When getting, the user agent that meets the requirements must return a FileReader or a FileReadersync object to read the total number of bytes, if the BLOB does not have to read bytes, return 0.
TYPE: Small-written ASCII encoded string represents the media type blob. At the time of acquisition, the user agent must bLOB returns the A type ASCII encoded string in lowercase, so when it converts to a byte sequence, it is a resolvable MIME type, or an empty string (0 byte) if it is The type cannot be determined.

Configuration function

Creating a blob object is essentially the same as the way to create another object, all using blob ( The constructor is created. The constructor accepts two parameters:

The first parameter is a data sequence, the format can be ArrayBuffer, ArrayBufferView, Blob, Domstring The second parameter is a two attributes containing the following. Object

TYPE: MIME type,

endings:Decide the data format of the first parameter. The default value is “transparent”, which specifies how the string containing the row end character N is written. It is one of the following two values: “Native”, indicating that the row end value will be changed to a newline character for the host operating system file system; “Transparent”, indicating that the end of the Save in BLOB will remain unchanged.

VAR DATA1 = “A”; var blob1 = new blob1 = new blob ([data1]); console.log (blob1); // Output: blob {size : 1, TYPE: “} var debug = {Hello:” world “}; var blob = new blob ([Json.Stringify (Debug, NULL, 2)], {type: ‘Application / JSON’}; console .log (blob) // Output BLOB (22) {Size: 22, Type: “Application / JSON”} // Create a 8-byte ArrayBuffer, create a 2-byte of each array element on it View “VAR ABF = New ArrayBuffer (8) VAR ABV = New INT16Array (ABF) VAR BOLB_ARRAYBUFFER = New Blob (Abv, {TYPE: ‘TEXT / Plain’}) Console.log (Bolb_ArrayBuffer) // Output BLOB (4) { Size: 4, TYPE: “Text / Plain”}
  • SLICE method
Blob object has a slice method Returns a new blob object, includingData within the specified range in the source BLOB object.
Slice (start, end, contentty)
START: Optional, represents blob The subscript indicates the starting position of the first one that will be copied into the new blob. If it is incoming a negative number, this offset will start from the end of the data from the end of the data.

END: Optional, representing a subscript of BLOB, the corresponding byte of this subscript -1 will be the last byte of the new blob being copied. If you pass a negative number, then this offset will start from the end of the data from the end of the data. ContentType: Optional, give a new BLOB to a new document type. This will set its TYPE attribute to the incoming value. Its default is an empty string.

VAR DATA = “abcdef”; var blob1 = new blob ([data]); var blob2 = blob1.slice (0, 3) Console.log (blob1); // Output: blob {size: 6, type: “} console.log (blob2); // Output: blob {size: 3, Type:”}

  Slice is used for file fragment upload  
Split and concurrent combination, dividing a large file into multiple pieces, and send it up, greatly improves large files. Upload speed.
When a network problem causes an error, it is only necessary to retransmit the missed fragmentation instead of the entire file. An additional slice transmission can be more real-time tracking upload progress.

Split upload logic is as follows:

To upload file objects, fragmenting files according to Chunk (small)

Upload each file by POST square foil, where quilt queryString is used to describe the current uploaded file information; POST Body This time, the binary data segment
interface is returned each time, it is used to perform the next upload
InitupLoad (); // Initialization upload Function INITUPLOAD () {var chunk = 100 * 1024; // Each size var input = document.getlementByid (“file”); // input file input.onchange = function (e) {var file = this.files [0] Var query = {}; var chunks = []; if (!! file) {var start = 0; // File Split FOR (VAR i = 0; i {Return KEY + “=” + query [key];}). Join (“&”); var xhr = new xmlhttpRequest (); xhr.Open (“post”, “http: // xxxx / opload?” + querystr); xhr.overridemimimeType (“Application / OCTET-stream “); // Get post body in binary data 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) {ix (xhr.status ==== 200) {var resp = json.parse (xhr.responsetext); // Interface Returns NextOffset // Resp = {// isfinish: False, // Offset: 100 * 1024 //} IF ( TYPEOF CB === “function”) { (this, resp, chunks, query)}}}}} // Perform Function SuccessPerupload (Resp, Chunks, Query) {if (Resp.isfinish === True) {Alert (“Upload Success”);} else {// Not uploaded Query.Offset = Resp.Offset; Upload (Chunks, Query, SuccessPerupload);}} // Get file binary data Function GetFilebinary ( File, cb) {var reader = new fileReader (); Reader.ReadasarayBuffer (file); reader.onload = function (e) {if (TyPEOF CB === “function”) { (this, this.Result);}}}

  • blob URL

When the URL of the BLOB protocol is used as the URL usage usage, it can be requested as a picture request address or as a file request address. Format:


 The following is an example of downloading files, directly calls    
// file is the file to download (blob objects) downloadHandler: function (file, fileName) {let link = document.createElement ( ‘a’) link.href = window.URL.createObjectURL (file) = fileName () window.URL. RevokeObjecturl (Link.href) IF (Navigator.Useragent.indexof (‘Firefox’)> -1) {const a = document.createElement (‘a’) a.addeventListener (‘Click’, Function (E) { = filename a.href = url.createObjectURL (file)}) let e = document.createEvent (‘mouseevents’) E.INITEVENT (‘Click’, false, false) a.dispatchevent (e)}}

Set the return type to BLOB

VAR x = new xmlhttpRequest (); x.responsetype = ‘blob’; // Return A blob object

Difference between BLOB URL and DATA URL

The length of the BLOB URL is generally short, but the DATA URL is directly stored data encoded by the picture base64. It is often very long, as shown above, the browser uses the omitted number (…) when displaying the Data URL. When explicit large pictures, use BLOB URLs to get better possibilities. The BLOB URL can easily use XMLHttpRequest to obtain source data, such as setting the data type returned by XMLHttpRequest to blob

Blob URL can only be used inside the current application, copy the BLOB URL to the browser In the address bar, it is not possible to obtain data. Compared to Data URLs, there is a good portability and can be used in any browser.

   The above is the full content of this article, I hope this paper has a certain reference value for everyone's learning or work.If you have any questions, you can leave a message, thank you for your support of Tumi Cloud. 
© Copyright Notice
Just support it if you like
comment Grab the couch

Please log in to comment