SoFunction
Updated on 2025-04-10

Summary of related operation methods of FileReader in Js

Preface

FileReader is an object in js that reads files asynchronously. It can read file contents in different formats. Before talking about FileReader objects, we will first introduce two objects.Blob ObjectsandFile object.

Blob Objects

BlobObject represents an immutable, original data-like file object. In other words, once a Blob object is defined, it cannot be modified.

How to build a blob object?

Constructed by constructor

let blob = new Blob(["Hello"], {type: "text/plain"})
(blob)
//The return value is:// Blob {size: 7, type: 'text/plain'}

Next, let’s explain the meaning of these two parameters separately:

The first parameter:Receive an array (array), which can store any type of data, and these data will be stored in the blob.

The second parameter:Receive an object, which is an optional object, and contains two properties:

  • Type attribute:Will be stored in the blobMIME data type (a way to identify file data type), such as type/plain, type/html, image/jpeg, etc.

    endings attribute:Specifies how to handle ending characters when a blob is in text form. This parameter is only valid for Blob objects that store text data, and is invalid for binary Blob objects.

Blob-related properties and operations

Blob object has two properties, namely Size and type

let blob = new Blob(["Hello", "1", 1], {type: "text/html"})
//Get the total length of data stored in the blob()
//Get the data type stored in the blob//The data type here is essentially just to identify the storage type, which is considered a convention()

Blob objects have the following operation functions, which provide a convenient API to operate Blob data.

let blob = new Blob(["Hello", "1", 1], {type: "text/plain"})
/**
  * text() method
  * text method returns a Promise object, and returns data worthy of storage in the Blob by obtaining it.
  * @return Promise
  */
().then(res => {
    //The return value will merge the original data.    //Return: Hello11    (res)
})
/**
  * slice() method
  * slice method will slice the data in the blob and return a new blob object
  * @param start: Data interception start position (included)
  * @param end: Data interception terminate index position (not included)
  * @param contentType/type: The type of data stored in the new Blob object obtained after sharding is ''
  * @return Blob
  */
let newBlob = (0, 3)
(newBlob)
/**
  * stream()method
  * streammethod会返回一个可读流对象
  * This object allows us to read data in the Blob object block by block
  * @return ReadableStream
  */
let readableStream = ();
let reader = ();
().then(res => {
    (res)
    //The data returned here is ASCII code    // We can access the data in the array by accessing the data to achieve chunked access    ()
    (([6]))//1
    (([0]))//H
})
/**
  * arrayBuffer method
  * parse the data of the Blob object in binary form and return a Promise object
  * Arraybuffer object represents a common raw binary data buffer
  * @return Promise
  */
().then(res => {
    (res)//Output an ArrayBuffer object})

File object: Special Blob object

The File object is a special Blob object, which is usually used to identify the information of a single file uploaded by input.

Simply put, the File object is a subclass of the Blob object.

There are very few operations on File objects. The following are the specific properties and operations.

/***
  * @param fileBits: Accept an Array, where objects such as Blob, ArrayBuffer, strings are stored in Array
  * @param name: file name
  * @param options:{
  * type: MIME type, select the file type,
  * lastModified: The last time the file is modified
  * }
  * @type {File}
  */
let file=new File(["test"],"",{
    type:"text/plain",
})
(file)//Get file object()//Get the last modification time of the file()//Get the last modification time of the file and use the Date object to store it()//Get the file name

FileList object

A FileList object is simply a container that stores File objects. Usually, fileList requires us to get it by accessing the files array.

The specific properties of FileList are as follows:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<input type="file" >
<script>
    let files = ("file")
    ("change", (event) => {
        //Get fileList object by accessing files file list        let fileList = 
        (fileList)//View fileList object        //Use fileList's API to access the File object with the specified index        ((0))
    })
</script>
</body>
</html>

FileReader object

After laying the foundation for so long, I finally asked the owner of this article, FileReader.

FileReader object can access files uploaded by users in an asynchronous manner.

Three properties of FileReader

error: Returns the error message when reading

readyState: Return to the current state of the operation

value state describe
0 EMPTY Reader is created, but the read method is not called
1 LOADING Read method is called
2 DONE Complete the operation

result:Return the result of reading the file

The specific operations and attributes are as follows:

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<input type="file" >
<script>
    let fileReader = new FileReader();
    let files = ("file")
    ("change", (event) => {
        let fileList = 
        let file = fileList[0]
        ()//The function is not called, return 0        /**
          * Here readAsText accepts a Blob object. As mentioned before, the File object is a special Blob object.
          * So pass it directly into the file object
          * Here readAsText is used to read the file into text form
          * @param Blob accepts a blob object
          * @param encoding Set encoding format
          * @return undefined This function does not return a value
          * */
        // (file)
        //Call the termination function and terminate the file reading        // ()
        /**
          * readAsDataUrl method
          * This method will read the file and finally return a Base64-based URL into the result attribute
          * The url in the result here starts with data:
          * @param Blob accepts a blob object
          * @return undefined
          */
        // (file)
        /**
          * readAsArrayBuffer method
          * This method will read and store the file as an ArrayBuffer, and finally return an ArrayBuffer array into the result
          * @param Blob accepts a blob object
          * @return undefined
          * */
        (file)
    })
    /**
      * This method is called when read
      */
     = () => {
        ("Start Reading")
        ()//Calling the function, but not ending yet, return 1    }
    /**
      * This method is called when the read is successful
      */
     = () => {
        ("Read successfully")
        ()
        ()//The call is completed, return 2    }
    /**
      * This method is called at the end of reading
      */
     = () => {
        ("Read End")
    }
    /**
      * Triggered during reading
      */
     = (e) => {
        ("Reading")
        //Get the loaded data amount        ("loaded==>" + )
    }
    /**
      * This method is fired when calling the abort function
      */
     = () => {
        ("Operation terminates")
    }
    //Free when reading fails     = () => {
        ("An error occurred")
        ()
    }
</script>
</body>
</html>

This method is used to create a temporary url containing the specified object. The life cycle of this url will be bound to the life cycle of the window that creates it. If the window that creates it is closed, the url will also be invalid.

Generally speaking, File objects or Blob objects will be passed into the function as parameters, and this temporary url will represent these objects.

Here is a case: This case generates a corresponding temporary url based on the image file passed by the user, and passes the temporary url as src to the img tag

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
<input type="file" >
<img  >
<script>
    let file = ("file")
    let ig = ("ig")
    ("change", (e) => {
        let fileList=
        //Get a document first        //What you get here is the File object        let file = fileList[0]
        //Because the file is also a Blob object, you can pass it in directly        =(file)
    })
</script>
</body>
</html>

Summarize

This is the end of this article about FileReader-related operation methods in Js. For more related operation content of FileReader, please search for my previous articles or continue browsing the following related articles. I hope everyone will support me in the future!