File API Files Operation FileReader

Source: Internet
Author: User

Recent research on point-to-point file transfer, think of a scheme filereader+webrtc.

When I see FileReader, oh, good things ah, carefully look at the file API, or called the Web API.

File API Official document file API

Some of the MDN's open Web apis| MDN

It mainly consists of, filelist,blob,file,filereader and so on.

Here we mainly discuss the FileReader, first look at the official website interface definition

[Constructor, exposed=Window,worker]InterfaceFilereader:eventtarget {//Async Read Methods    voidReadasarraybuffer (blob blob); voidReadastext (blob blob, optional domstring label); voidReadasdataurl (blob blob); voidabort (); //states    ConstUnsigned ShortEMPTY =0; ConstUnsigned ShortLOADING =1; ConstUnsigned ShortDone =2; ReadOnlyAttribute unsigned ShortreadyState; //File or Blob data    ReadOnlyAttribute (domstring or ArrayBuffer)?result; ReadOnlyAttribute Domerror?error; //event handler Attributesattribute EventHandler Onloadstart;    Attribute EventHandler onprogress;    Attribute EventHandler onload;    Attribute EventHandler onabort;    Attribute EventHandler onerror;  Attribute EventHandler onloadend; };

First can be seen, he inherited is Eventtarget, this shows what, haha, the following is the main properties, methods, events, it is best to refer to the official Website API documentation.

Main properties

Readysate: status, corresponding to three enumeration values, Empty,loading,done

Result: After reading the content, the general onload after the call.

Error: Wrong, notfounderror,securityerror,notreadableerror

Main methods:

Readasarraybuffer:

Readastext:

Readasdataurl:

Main events:

Onloadstart: Ready to start reading

OnProgress: in Reading or decoding

OnLoad: Read complete

Onbort: terminating, such as calling the Abort method

OnError: Error occurred

  Onloadend: Read operation completed, whether read succeeded or failed

I will not say much, the walkthrough today is Readastext, I think of the scene is online text comparison, online JSON format, online text editing.

Come on, teenager, online JSON format, 50 lines of code to do a demo.

Source Path: Https://github.com/xiangwenhu/BlogCodes

HTML code:

<!DOCTYPE><HTML><Head>    <title>The Readastext of FileReader</title></Head><Bodystyle= "Margin:2rem Auto">    <DivID= "Container"style= "Margin-left:5rem">        <inputtype= "File"ID= "File"onchange= "Handlefiles (this.files)" />        <DivID= "Results"></Div>    </Div></Body><Scriptsrc= "Js/readastext.js"></Script></HTML>

JS Code:

functionhandlefiles (files) {if(files.length) {Let file= Files[0], reader =NewFileReader () reader.onload= () + = {            (NewJsonparser (Reader.result, ' #results ') . Init ()} reader.readastext (file)}}class Jsonparser {constructor (source, selector) {
     This. Source =Source This. selector =selector This. Results = []         This. Deep = 0} init () {Try{Let JSON= Json.parse ( This. Source) This. Format (undefined, JSON) Document.queryselector ( This. selector). InnerHTML = This. Results.join (' <br/> ')        } Catch(e) {alert (e)}} format (Key= ' ', value) {        if(ValueinstanceofArray) {             This. Results.push ( This. Generateline (Key, ' ['))             This. deep++Value.foreach (V, i)= {                 This. Format (i, v)})  This. deep-- This. Results.push ( This. Generateline (Undefined, '] '))        } Else if(Value &&typeofValue = = ' object ') {             This. Results.push ( This. Generateline (Key, ' {')) ) Object.keys (value). ForEach (k= {                 This. deep++ This. Format (k, value[k]) This. deep--            })             This. Results.push ( This. Generateline (Undefined, '} '))        } Else {             This. Results.push ( This. Generateline (key, value))} } generateline (key, value) {Let K= Key = = = Undefined | | Key = = = '? ‘‘: ' ${key}: ', v= value = = =NULL? ' NULL ': Valuereturn' Repeat '. This. Deep) +' ${k}${v} '} 

Effect:

  

File API Files Operation FileReader

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.