Table of Contents
FileReader
Creation
Methods
Events in the properties
In order to better handle file reading
Home Web Front-end H5 Tutorial Specifically analyze the encapsulation of HTML5 file reading FileReader and file reading module

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

Mar 11, 2017 pm 04:04 PM

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!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Table Border in HTML Table Border in HTML Sep 04, 2024 pm 04:49 PM

Guide to Table Border in HTML. Here we discuss multiple ways for defining table-border with examples of the Table Border in HTML.

Nested Table in HTML Nested Table in HTML Sep 04, 2024 pm 04:49 PM

This is a guide to Nested Table in HTML. Here we discuss how to create a table within the table along with the respective examples.

HTML margin-left HTML margin-left Sep 04, 2024 pm 04:48 PM

Guide to HTML margin-left. Here we discuss a brief overview on HTML margin-left and its Examples along with its Code Implementation.

HTML Table Layout HTML Table Layout Sep 04, 2024 pm 04:54 PM

Guide to HTML Table Layout. Here we discuss the Values of HTML Table Layout along with the examples and outputs n detail.

HTML Input Placeholder HTML Input Placeholder Sep 04, 2024 pm 04:54 PM

Guide to HTML Input Placeholder. Here we discuss the Examples of HTML Input Placeholder along with the codes and outputs.

HTML Ordered List HTML Ordered List Sep 04, 2024 pm 04:43 PM

Guide to the HTML Ordered List. Here we also discuss introduction of HTML Ordered list and types along with their example respectively

Moving Text in HTML Moving Text in HTML Sep 04, 2024 pm 04:45 PM

Guide to Moving Text in HTML. Here we discuss an introduction, how marquee tag work with syntax and examples to implement.

HTML onclick Button HTML onclick Button Sep 04, 2024 pm 04:49 PM

Guide to HTML onclick Button. Here we discuss their introduction, working, examples and onclick Event in various events respectively.

See all articles