Home > Web Front-end > H5 Tutorial > body text

Specifically analyze the encapsulation of HTML5 file reading FileReader and file reading module

黄舟
Release: 2017-03-11 16:04:57
Original
2344 people have browsed it

FileReader is an important part of File-API
Used to read local files

FileReader

Creation

To use the file reading function
It is also necessary to instantiate the FileReader object

var fr = new FileReader();
Copy after login

It provides us with some interface methods and events

Methods

5 methods can be called through the instance object
4 of them A specified file reading method
Another method used to interrupt file reading

APIParametersDescription
FileReader.readAsBinaryStringFile/BlobThe file is read as a binary string, each byte contains a 0 to An integer between 255
FileReader.readAsTextFile/Blob[,encoding]The file is read as a text string. The default text encoding is 'UTF-8', other encodings can be specified via optional parameters
FileReader.readAsDataURLFile/BlobThe file is read as a Data-URI object based on Base64 encoding
FileReader.readAsArrayBufferFile/BlobThe file is read as an ArrayBuffer Object
abort()NoneAbort file reading

Note: Blob (Binary Large Object) is a binary object

No matter whether the file is read successfully or not
These functions will not have any return value
The read file result is stored in the result of the instantiated FileReader object

Events in the properties

In addition to the above methods, the file reading object also contains a complete set of event models
for capturing various states during file reading

  • onloadstart : Start reading

  • onprogress : Reading

  • onload : Read Success

  • onerror : Read error

  • onabort : Read interrupt

  • onloadend : Read Retrieval is completed (regardless of success or failure)

Use

Now we use this Filereader to read a local image

html is as follows
Simply create a file to read Get the button input
and an img tag used to display the read image

<input type="file" id="choose"><br><br><img src="" id="image" width=&#39;200px&#39; height=&#39;200px&#39;>
Copy after login

##js script is as follows
var choose = document.getElementById(&#39;choose&#39;);var img = document.getElementById(&#39;image&#39;);
choose.onchange = function(){
  showImg(this, img);
}function showImg(chooseDom, imgDom){
  var file = chooseDom.files[0]; //获取FileList对象的第一个元素——一个File对象
  var fr = new FileReader(); //实例化FileReader对象
  fr.onload = function(e){ 
    imgDom.src = e.target.result; //e.target引用fr
  }
  fr.readAsDataURL(file); //读取为DataURL}
Copy after login

After getting the node

Bind the change event to the input tag

In this way, every time a file is selected, the showImg function will be called to read it

Verify that the read content can be checked file.type

if(!/image\/\w+/.test(file.type)){  
    //...
    return false;  
}
Copy after login

Or if you want to read text
, just use readAsText

<input type="file" id="choose"><br><br><p id="demo"></p>
Copy after login
var choose = document.getElementById(&#39;choose&#39;);
var demo = document.getElementById(&#39;demo&#39;);
choose.onchange = function(){
  showText(this, demo);
}function showText(chooseDom, textDom){
  var file = chooseDom.files[0];  var fr = new FileReader();
  fr.onload = function(e){
    textDom.innerHTML = e.target.result;
  }
  fr.readAsText(file);
}
Copy after login

File reading module

In order to better handle file reading

We need to encapsulate a file reading module

//events事件回调对象包含
success,load,progressvar FileLoader = function (file, events) {
    this.reader = new FileReader();    
    this.file = file;    
    this.loaded = 0;    
    this.total = file.size;    
    this.step = 1024 * 1024;//每次读取1M
    this.events = events || {};    
    this.bindEvent();    
    this.readBlob(0);//读取第一块}
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、error回调暂无
    },
    onProgress: function (loaded) {
        var percent,
            handler = this.events.progress;        
            this.loaded += loaded;
        percent = (this.loaded / this.total) * 100;
        handler && handler(percent);
    },    // 读取结束(每一次执行read结后调用)
    onLoad: function () {
        var handler = this.events.load;        
        // 在此发送读取的数据
        handler && handler(this.reader.result);        
        // 如果未读取完毕继续读取
        if (this.loaded < this.total) {            
        this.readBlob(this.loaded);
        } else {            
        // 读取完毕
            this.loaded = this.total;            
            // 如果有success回调则执行
            this.events.success && this.events.success();
        }
    },    // 读取文件内容
    readBlob: function (start) {
        var blob,
            file = this.file;        
            // 若支持slice方法,则分步读取,不支持就一次性读取
        if (file.slice) {
            blob = file.slice(start, start + this.step + 1);
        } else {
            blob = file;
        }        this.reader.readAsText(blob);
    },    
    // 中止读取
    abort: function () {
        var reader = this.reader;        
        if(reader) {
            reader.abort();
        }
    }
}
Copy after login

The above is the detailed content of Specifically analyze the encapsulation of HTML5 file reading FileReader and file reading module. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!