Example of JavaScript FileReader API processing files

allway2 2022-06-24 07:23:33 阅读数:935

examplejavascriptfilereaderapiprocessing

File reader API Provide File reader object , It can be used to read files from the local computer and use their data on Web pages . You can even use it to read files from the client's local computer , Then transfer its data to the server .

Reading a file and its data can be done in many ways , But sometimes it's best to use almost all Web Browsers support object\API. That's why FileReader API yes vanilla JavaScript One of the most common objects used to read the contents of a file in .

File reader objects

To create a new file reader object , You need to use... First “new” Key word call FileReader() Constructors . after , You are ready to use the various functions of this object . To learn more about this constructor , You can click here visit MDN Official documents of .

Document reader method

The file reader object has many different methods to help us parse the data of the file being read . Some of these methods are automatically executed by the browser , It is called an event handler method , for example , Once the file reader has finished reading the contents of the file , Will automatically call “onload()” Method .

Method to access the file reader object , Please use Dot operator “.” .  Some of the methods and variables that can be accessed using the file reader object are :

  • object. result: Used to get the contents of the read file
  • object.readAsText: Read the contents of the file and parse it into text
  • object.abort: Abort the current read operation

More can be read on their official documentation page .

File reader example

For demo file readers API Use , We need one with type="file" Of the input field HTML Webpage , We can use HTML File to create it :

<center>
<input type="file" />
</center>

This will provide us with the following pages :

Be careful : We do not use any... In the input field id or class attribute , Because we will use the query selector to reference our input fields .

about JavaScript Code , The first thing we need to do is use the query selector to select the input field :

const input = document.querySelector(`input[type="file"]`);

Next , We'll look at the variables input Add a “change” Event listener , It will call a function to load the contents of the file using the following lines :

input.addEventListener("change", function (e) {
}, false);

Every time Enter the label This function event listener is executed whenever the file is loaded , We can use “input.file” Array to access the file . To display the details of the loaded file , We can use the following lines :

console.log(input.files[0])

We get the following output on the console :

Inside the function , We will use the following lines to create a file reader object :

const reader = new FileReader();

The file I want to read is a text file , So here I will use the method of the file reader object readAsText Use the following lines to parse the contents of the file into text data :

reader.readAsText(input.files[0]);

Now? , We can use reader.result Access the contents of the file we read and parse . When the file reader object finishes reading the file , Automatically called onload() Method , So we can use the following command to display the contents of the file after reading :

reader.onload = function () {
console.log(reader.result);
};

The complete code snippet is :

<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<input type="file" />
</center>
<script>
const input = document.querySelector(`input[type="file"]`);
input.addEventListener(
"change",
function (e) {
console.log(input.files[0]);
const reader = new FileReader();
reader.readAsText(input.files[0]);
reader.onload = function () {
console.log(reader.result);
};
},
false
);
</script>
</body>
</html>

Run the file and select a text file on your local computer , As shown below :

You will observe the following results on the console :

Come here , You have read the contents of the files and printed them to the console .

Use images

To read the image and display it on the console , You need to first use the following line to read the text with readAsDataURL The file of :

reader.readAsDataURL(input.files[0]);

To display an image on a web page , You need to use the following lines in onload() Function to create a new Image Variable :

reader.onload = function () {
const img = new Image();
};
},

And then here onload Function , You will set the source of the image variable we created equal to the result of the file reader object :

img.src = reader.result;

Last , We will append this image variable to... Using the following lines Document:

document.body.appendChild(img);

The complete code snippet is :

<!DOCTYPE html>
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<center>
<input type="file" />
</center>
<script>
const input = document.querySelector(`input[type="file"]`);
input.addEventListener(
"change",
function (e) {
console.log(input.files[0]);
const reader = new FileReader();
reader.readAsDataURL(input.files[0]);
reader.onload = function () {
const img = new Image();
img.src = reader.result;
document.body.appendChild(img);
};
},
false
);
</script>
</body>
</html>

After running the file , You will get the following output :

Okay , Now you know how to use File Reader API To read the files on the local computer

Conclusion

File reader API Yes with native JavaScript The built-in API, Almost all Web Browsers support . This file reader API Return us a file reader object , We can read the contents of the file by selecting the parsing method . In this article , We learned about file readers API、 File reader object and how to use the file reader object to read text files and image files . We even add images to the document to Web Display image on browser .

copyright:author[allway2],Please bring the original link to reprint, thank you. https://en.javamana.com/2022/175/202206240117230033.html