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

Docker uses Supervisor to manage process operations

A Docker container starts a single process when i...

CentOS 8 installation diagram (super detailed tutorial)

CentOS 8 is officially released! CentOS fully com...

Introduction and use of js observer mode

Table of contents I. Definition 2. Usage scenario...

Detailed explanation of the functions and usage of MySQL common storage engines

This article uses examples to illustrate the func...

Examples of using the ES6 spread operator

Table of contents What are spread and rest operat...

How to add fields and comments to a table in sql

1. Add fields: alter table table name ADD field n...

Detailed example of removing duplicate data in MySQL

Detailed example of removing duplicate data in My...

How to redirect PC address to mobile address in Vue

Requirements: The PC side and the mobile side are...

Detailed steps for building Portainer visual interface with Docker

In order to solve the problem mentioned last time...

Theory: The two years of user experience

<br />It has been no more than two years sin...

js implements a simple English-Chinese dictionary

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

Use CSS to implement special logos or graphics

1. Introduction Since pictures take up a lot of s...