FileReader reads local files

FileReader is an asynchronous file reading mechanism, which can easily read local files in combination with input:file.

一、input:type[file]

  An input of type file is rendered as a button and a piece of text. Clicking the button opens a file selection window with a textual description of the file (in most cases the file name). The input of the file type will have the files attribute, which saves the relevant information of the file.

<input type="file" name=""  id="fileBox">

 Click the button, upload a file, enter inputElement.files in the console, and print the file information:

   

  lastModified: value, indicating the number of milliseconds of the last modification time;

  lastModifiedDate: object, representing the last Date object representing the latest modification time;

  name: the file name in the local file system;

  size: the size of the file in bytes;

  type: string, MIME type of the file;

  webkitRelativePath: This is empty; when the webkitdirectory attribute is added to the input, the user can select a folder. At this time, weblitRelativePath represents the relative path of the file in the folder . for example:

 <input type="file" id="inputBox" webkitdirectory>

  After clicking the button to add a folder containing 3 files, the console prints inputBox.files as follows:

At this point weblitRelativePath represents the path of the file of the current file object in the folder.

Second, FileReader

  The file object only obtains the description information of the file, but does not obtain the data in the file, and inputBox.value only saves the absolute path of the file.

  

  The data in the file is read through the FileReader provided by H5, so some browsers do not have a FileReader object, which needs to be verified when applying.

  1. First, you need to instantiate a FileReader object.

var reader = new FileReader();

  2. Methods provided by FileReader:

  ①readAsArrayBuffer(file): Read the file content by bytes, and the result is represented by an ArrayBuffer object;

  ②readAsBinaryString(file): Read the file content in bytes, and the result is the binary string of the file;

  ③readAsDataURL(file): Read the content of the file, and the result is expressed in the form of a string of data:url;

  ④readAsText(file,encoding): Read the content of the file by characters, and the result is expressed in the form of a string;

  ⑤abort(): Terminate the file read operation.

  Among them, readAsDataURL and readAsText are more commonly used, and only these two are described here.

  3.1 readAsDataURL will base64 encode the file content and output:

1  var inputBox = document.getElementById("inputBox" );
 2 inputBox.addEventListener("change", function (){
 3    var reader = new FileReader();
 4    reader.readAsDataURL( inputBox.files[0] ); // Initiate an asynchronous request 
5    reader.onload = function (){
 6 // After the reading is completed, the data is saved in the result property of the object 7      console.log( this .result);//base64 content display
 8   }
 9 })      
 

  3.2 Due to the src attribute of the media file, it can be displayed by using the network address or base64, so we can use readAsDataURL to preview the image.

1 <input type="file" id="inputBox" >
2 <img src="" id="img">
1  var inputBox = document.getElementById("inputBox");
 2  var img = document.getElementById("img");
 3  inputBox.addEventListener(" change ",function(){
 4    var reader = new FileReader();
 5    reader .readAsDataURL(inputBox.files[0]);//Initiate an asynchronous request
 6 reader.onload    = function(){
  7      //After the reading is completed, assign the result to the src of img
 8      img.src = this.result;
 9    }
 10 })

Just assign the read result to the src attribute of the image to preview the image:

  4. readAsText(file, encoding) can read the file according to the specified encoding method, but the unit of reading the file is character, so for text files, just read according to the specified encoding method; for media files (picture, audio, etc.) , video), its internal composition is not arranged by characters, so using readAsText to read will generate garbled characters, so it is not the most ideal way to read files.

  5. Events provided by FileReader

  ①onabort: called when the read operation is aborted ;

  ②onerror is called when an error occurs in the read operation ;

  ③onload is called when the read operation is successfully completed ;

  ④onloadend is called when the read operation is completed, regardless of success or failure ;

  ⑤onloadstart is called when the read operation starts ;

  ⑥ onprogress is called periodically during the process of reading data .

 1 var inputBox = document.getElementById("inputBox");
 2 var count=0;
 3 inputBox.addEventListener("change",function(){
 4   var reader = new FileReader();
 5   reader.readAsText(inputBox.files[0],"utf-8");//发起异步请求
 6   reader.onload = function(){
 7     console.log("加载成功")
 8   }
 9   reader.onloadstart = function(){
10      console.log("Start loading" )
 11    }
 12    reader.onloadend = function (){
 13      console.log("Loading finished" )
 14   }
 15 reader.onprogress = function ( ){
 16      count++    ; 17      console.log (
 "Loading" + count)
 18   }
 19 })  

 Console result:

Every 50ms or so, a progress event will be triggered. For larger files, progress can be used to implement a progress bar.

The onload event fires before onloadend.

When the file cannot be read for various reasons, the error event will be triggered. When the error event is triggered, the relevant information is saved in the error attribute of the FileReader object, which will save an object with only one attribute code, the error code. 1 means file not found, 2 means security error, 3 means read interrupted, 4 means file is unreadable, 5 means encoding error .

If you want to interrupt the reading process, you can call the abort method, which will trigger the abort event.

No matter which of the load, error, and abort events are triggered, the loadend event will eventually be triggered.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325082446&siteId=291194637