How to get the contents of .txt file through FileReader in JS

How to get the contents of .txt file through FileReader in JS

JS obtains the .txt file content through FileReader

Recently, I have been dealing with a requirement to parse .txt files through js to do some processing. Here is a summary.

Read .txt file method

var reader = new FileReader();
var fileUploader = document.getElementById("fileUploader"); //Get the input box id to get the file information reader.readAsText(fileUploader.files[0], "utf-8"); //Set the encoding reader.onload = function() { undefined
data.trim().split('\n').forEach(function(v, i){undefined
window['str' + (i+1)] = v
}
}
  • v is the content of each line of text in .txt
  • i is the line number in .txt

There is no direct method to get the total number of lines in a .txt file, so I use a loop to handle it here:

var count =0;
data.trim().split('\n').forEach(function(v, i){undefined
count++;
})

JS: FileReader() reads files

The FileReader object allows a Web application to asynchronously read the contents of a file (or raw data buffer) stored on the user's computer, using a File or Blob object to specify the file or data to read.

property:

  • FileReader.error indicates an error occurred while reading a file
  • FileReader.readyState
  • The result read FilerReader.result

Let's start with a practical example

index.html is as follows

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>FileReader</title>
</head>
<body>
<input id="input" type="file">
</body>
</html>

demo.txt is as follows

This is a demo test

hello world

Reading txt files

<script>
  const input = document.querySelector('input[type=file]')
  input.addEventListener('change', ()=>{
    const reader = new FileReader()
    reader.readAsText(input.files[0],'utf8') // input.files[0] is the first file reader.onload = ()=>{
      document.body.innerHTML += reader.result // reader.result is the result}
  }, false)
  </script>

Reading image files

<script>
  const input = document.querySelector('input[type=file]')
  input.addEventListener('change', ()=>{
    console.log( input.files )
    const reader = new FileReader()
    reader.readAsDataURL(input.files[0]) // input.files[0] is the first file reader.onload = ()=>{
      const img = new Image()
      img.src = reader.result
      document.body.appendChild(img) // reader.result is the result of the acquisition}
  }, false)
  </script>

Examples

import java.io.*;
public class FileRead {
    public static void main(String args[]) throws IOException {
        File file = new File("Hello1.txt");
        // Create a file file.createNewFile();
        // creates a FileWriter Object
        FileWriter writer = new FileWriter(file);
        // Write content to the file writer.write("This\n is\n an\n example\n");
        writer.flush();
        writer.close();
        // Create a FileReader object FileReader fr = new FileReader(file);
        char[] a = new char[50];
        fr.read(a); // Read the contents of the array for (char c : a)
            System.out.print(c); // Print characters one by one fr.close();
    }
}

method

Method Definition describe
abort():void Terminates a file read operation
readAsArrayBuffer(file):void Asynchronously read the file contents byte by byte, and the result is represented by an ArrayBuffer object
readAsBinaryString(file):void Asynchronously read the file content by bytes, and the result is a binary string of the file
readAsDataURL(file):void Asynchronously read the file content, and the result is represented by a string in the form of data:url
readAsText(file,encoding):void Asynchronously read the file content character by character, and the result is expressed as a string

event

Event Name describe
onabort Called when a read operation is aborted
onerror Called when an error occurs in a read operation
onload Called when the read operation completes successfully
onloadend Called when the read operation completes, whether successful or unsuccessful.
onloadstart Called before a read operation is about to begin
onprogress Called periodically during data reading

The above is my personal experience. I hope it can give you a reference. I also hope that you will support 123WORDPRESS.COM.

You may also be interested in:
  • JavaScript reads files through the filereader interface
  • JS+HTML5 FileReader object usage example
  • JS+HTML5 FileReader implements local preview function before file upload

<<:  A brief discussion on the magical uses of CSS pseudo-elements and pseudo-classes

>>:  How to use dl(dt,dd), ul(li), ol(li) in HTML

Recommend

js implements the pop-up login box by clicking the pop-up window

This article shares the specific code of js to re...

Summary of constructor and super knowledge points in react components

1. Some tips on classes declared with class in re...

About the problem of running git programs in jenkins deployed by docker

1. First, an error message is reported when assoc...

How to use geoip to restrict regions in nginx

This blog is a work note environment: nginx versi...

Significantly optimize the size of PNG images with CSS mask (recommended)

This article is welcome to be shared and aggregat...

How to configure pseudo-static and client-adaptive Nginx

The backend uses the thinkphp3.2.3 framework. If ...

HTML Basics: HTML Content Details

Let's start with the body: When viewing a web ...

Explanation of MySQL index types Normal, Unique and Full Text

MySQL's index types include normal index, uni...

Simple implementation of html hiding scroll bar

1. HTML tags with attributes XML/HTML CodeCopy co...

Example code for implementing dotted border scrolling effect with CSS

We often see a cool effect where the mouse hovers...

How to solve the error of connecting to the database when ServerManager starts

Servermanager startup connection database error R...

Common parameters of IE web page pop-up windows can be set by yourself

The pop-up has nothing to do with whether your cur...

Detailed tutorial on installing MySQL 8.0.19 in zip version on win10

Table of contents 1. After downloading, unzip it ...

JavaScript Factory Pattern Explained

Table of contents Simple Factory Factory Method S...