Introduction to HTML5 FileReader distribution and file reading methods,
This article introduces the distribution of HTML5 FileReader reading files and its methods. The details are as follows:
Old rules first
First, we will introduce some methods and events of FileReader in H5.
FileReader Method
Name |
Function |
About () |
Terminate read |
ReadAsBinaryString (file) |
Read the file as a binary code. |
ReadAsDataURL (file) |
Read the file as DataURL Encoding |
ReadAsText (file, [encoding]) |
Read a file as text |
ReadAsArrayBuffer (file) |
Read the file as arraybuffer |
FileReader event
Name |
Function |
Onloadstart |
Triggered when reading starts |
Onprogress |
Reading |
Onloadend |
Read completion trigger, whether successful or failed |
Onload |
Triggered when the file is read successfully. |
Onabort |
Triggered upon interruption |
Onerror |
Triggered when an error occurs |
Code
The core idea of reading files in a distributed manner is to split files into blocks and read each MB.
HTML section
<! DOCTYPE html>
LoadFile. js
/** File reading module * file object * events event return objects including success, load, progress */var FileLoader = function (file, events) {this. reader = new FileReader (); this. file = file; this. loaded = 0; this. total = file. size; // read 1 M this each time. step = 1024*1024; this. events = events | {}; // read the first this. readBlob (0); this. bindEvent ();} FileLoader. prototype = {bindEvent: function (events) {var _ this = this, reader = this. reader; reader. onload = function (e) {_ this. onLoad () ;}; reader. onprogress = function (e) {_ this. onProgress (e. loaded) ;}; // start, abort, and error Callbacks are not added at the moment}. // The onss event returns onProgress: function (loaded) {var percent, handler = this. events. SS; // progress bar this. loaded + = loaded; percent = (this. loaded/this. total) * 100; handler & handler (percent) ;}, // read end (called at the end of each read execution, not the whole) onLoad: function () {var handler = this. events. load; // The read data handler & handler (this. reader. result); // continue reading if (this. loaded <this. total) {this. readBlob (this. loaded);} else {// read completed this. loaded = this. total; // If success is returned, execute this. events. success & this. events. success () ;}}, // read the file content readBlob: function (start) {var blob, file = this. file; // if the slice method is supported, read it step by step. if not, read if (file. slice) {blob = file. slice (start, start + this. step);} else {blob = file;} this. reader. readAsText (blob) ;}, // stop reading abort: function () {var reader = this. reader; if (reader) {reader. abort ();}}}
The above is all the content of this article. I hope it will be helpful for your learning and support for helping customers.