Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.


FileReader

FileReader allows Web applications to asynchronously read the contents of files (or raw data buffers) stored on the user’s computer, using File or Blob objects to specify files or numbers to read.

attribute

attribute instructions The return value
readyState Provides the current state of the FileReader read operation. Number. 0: no data has been loaded. 1: Data is being loaded. 2: All read requests are complete
result Returns the contents of the file. This property is valid only after the read operation is complete A string or an ArrayBuffer (depending on which reading method is used)
error Returns an error message while reading the file DOMError

The event processing

The event instructions
onloadstart Triggered when the read operation starts
onprogress Read time trigger
onload Triggered when the read operation is complete
onloadend Fired at the end of a read operation (either successful or failed)
onabort Triggered when the read operation is interrupted
onerror Triggered when an error occurred in the read operation

With event handlers, look at the readyState for each phase:

 <input id="test" type="file" onchange="getFile" />
Copy the code
function getFile(){
   const file = document.querySelector('#test').files[0];
   const reader = new FileReader();
   console.log("readyState = ", reader.readyState)
   reader.onloadstart = () = >{ console.log("onloadstart readyState = ", reader.readyState) }
   reader.onprogress = () = >{ console.log("onprogress readyState = ", reader.readyState) }
   reader.onload = () = >{ console.log("onload readyState = ", reader.readyState) }
   reader.onloadend = () = >{ console.log("onloadend readyState = ", reader.readyState) }
   reader.readAsDataURL(file);
}
Copy the code

Output result:

methods

methods instructions
abort Cancel the read of the FileReader and readyState will be DONE once triggered.
readAsArrayBuffer Read a Blob or File as an ArrayBuffer object
readAsBinaryString Read Blob or File as the original binary format of the File
readAsDataURL Read Blob or File as a string in data:URL format (Base64 encoded)
readAsText Read Blob or File as content (as a string)
readAsArrayBuffer,readAsBinaryString,readAsDataURL,readAsTextAll four methods are:
  • Receives Blob or File objects
  • When the read is complete, readyState becomes DONE
  • The LoadEnd event is triggered
  • The result is read in the Result property

What do these four methods look like? I prepared a test.txt (with some fake text) and a test.png respectively for testing, and the output results are as follows:

readAsArrayBuffer

readAsBinaryString

readAsDataURL

readAsText

Test code:

<! -- Vue -->
<template>
  <div id="fileUpload">
    <h1>{{readType}}</h1>
    <h4>Read TXT file:<input id="txt" type="file" @change="getFile('txt')" />
    </h4>
    <h4>Read JPG files:<input id="jpg" type="file" @change="getFile('jpg')" />
    </h4>
    <div style="margin-top:20px;">
      <button style="margin:5px;" @click="setReadType('readAsArrayBuffer')" > readAsArrayBuffer </button> 
      <button style="margin:5px;" @click="setReadType('readAsBinaryString')" > readAsBinaryString </button> 
      <button style="margin:5px;" @click="setReadType('readAsDataURL')" > readAsDataURL </button> 
      <button style="margin:5px;" @click="setReadType('readAsText')" > readAsText </button> 
    </div>
  </div>
</template>

<script>
export default {
  name: "fileUpload".data() {
    return {
      readType:'readAsArrayBuffer'
    };
  },
  methods: {
    setReadType(type){
      this.readType = type;
      document.querySelector('#txt').value = ' ';
      document.querySelector('#jpg').value = ' ';
    },
    getFile(type){
      const file = document.querySelector(` #${type}`).files[0];
      const reader = new FileReader();
      reader.onload = () = >{
        console.log(` reads.${type}The result is: ',reader.result);
        this[`${type}Res`] = reader.result;
      }
      reader[this.readType](file); }}};</script>
Copy the code

Refer to the link

MDN:https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader