js uses FileReader to read local files or blobs

js uses FileReader to read local files or blobs

FileReader reads local files or blobs

The FileReader object provides asynchronous reading of the contents of files stored on the user's computer. Use the File or Blob object to specify the file or data to be read. The FileReader interface provides methods for reading files and an event model that includes the reading results.

1. Use of FileReader

Note: If you need to be compatible with older browsers, you need to check whether the FileReader object exists.

if (window.FileReader) {
 let reader = new FileReader();
} else {
 console.log('Your browser does not support reading files');
}

2. FileReader Methods

method effect parameter Return Value
abort() Abort read operation none none
readAsArrayBuffer() Read file and Blob content file/blob The result property returns the file contents of the ArrayBuffer data object
readAsBinaryString()[deprecated by W3] Read file and Blob content file/blob The result property returns the file contents of the original binary data
readAsDataURL() Read file and Blob content file/blob

The result attribute returns the file content in the Base64 string format of data:URL

readAsText() Read file and Blob content file/blob The result property returns the file contents as a string

3. FileReader properties

  • FileReader.error (read-only): An exception indicating an error that occurred while reading a file
  • FileReader.readyState (read-only): A number representing the state of the FileReader
value Status Name describe
0 EMPTY No data loaded
1 LOADING Data loading
2 DONE

Data loading completed

  • FileReader.result (read-only): The contents of the file are read. This property is valid only after the data is read. The format of the file contents is determined by the reading method.

4. FileReader events

  • FileReader.onabort : This event is triggered when reading is aborted.
  • FileReader.onerror : This event is triggered when an error occurs while reading.
  • FileReader.onload : This event is triggered when reading is completed.
  • FileReader.onloadstart : This event is triggered when the read operation just starts.
  • FileReader.onloadend : This event is triggered when the reading is completed (it will be triggered both when it fails and when it succeeds).
  • FileReader.onprogress : This event is triggered while reading.

Notice:

1. Due to security reasons, FileReader reads files passed in by input or files returned by ajax reading server, and cannot read files in the specified path.

2. FileReader can be used in webworker.

<!DOCTYPE html>
<html class="no-js">
	<head>
		<meta charset="utf-8" />
		<meta http-equiv="X-UA-Compatible" content="IE=edge" />
		<title></title>
		<meta name="description" content="" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<link rel="stylesheet" href="" />
	</head>
 
	<body>
		<input type="file" id="myFile" />
		<script type="text/javascript">
			if (window.FileReader) {
				var reader = new FileReader();
			} else {
				console.log('Your browser does not support reading files');
			}
			var myFile = document.querySelector('#myFile');
			myFile.onchange = function () {
				var file = myFile.files[0];
				reader.readAsDataURL(file);
				reader.onload = function () {
					var data = reader.result; //file content in base64 format };
                reader.onerror = function(){
                    console.log('Read failed');
                    console.log(reader.error);
                }
			};
		</script>
	</body>
</html>

Problems with using FileReader to read local disk files

Execute a js file (place the js file under the src of the project)

(1) java.net.URL url = TestScriptEngine.class.getClassLoader().getResource("a.js");
(2)//System.out.println(url.getPath().substring(1).replace("%20", " "));
(3)FileReader fileReader = new FileReader(url.getPath());

Runtime

Appear: Exception in thread "main" java.io.FileNotFoundException: D:\Eclipse%20WorkSpace\(java300)ScriptManager\bin\a.js (The system cannot find the path specified)

If I change url.getPath() to "D:/Eclipse WorkSpace/(java300)ScriptManager/bin/a.js" my local file directory, I can read the file successfully

The value of url.getPath() is: D:\Eclipse%20WorkSpace\(java300)ScriptManager\bin\a.js But the loading file cannot be found

The problem is "%20". There is a space between Eclipse WorkSpace, and the system automatically replaces it with %20, causing an error during operation.

Do some processing on url.getPath(), replace %20 with " " space by url.getPath().substring(1).replace("%20", " "); the problem is solved

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:
  • How to get the full path of the file control in js?
  • JavaScript combined with fileReader to upload pictures
  • Javascript File and Blob Detailed Explanation
  • Conversion between file, bolb and base64 images in js image upload

<<:  CSS screen size adaptive implementation example

>>:  How to use crontab to backup MySQL database regularly in Linux system

Recommend

Detailed explanation of using javascript to handle common events

Table of contents 1. Form events 2. Mouse events ...

How to hide and forge version number in Nginx

1. Use curl command to access by default: # curl ...

Analyzing the MySql CURRENT_TIMESTAMP function by example

When creating a time field DEFAULT CURRENT_TIMEST...

Detailed steps to deploy lnmp under Docker

Table of contents Pull a centos image Generate ng...

Detailed explanation of Docker Swarm concepts and usage

Docker Swarm is a container cluster management se...

Detailed usage of Vue more filter widget

This article example shares the implementation me...

Using Vue3 (Part 1) Creating a Vue CLI Project

Table of contents 1. Official Documentation 2. Cr...

MySQL uses the truncate command to quickly clear all tables in a database

1. Execute the select statement first to generate...

Optimization methods when Mysql occupies too high CPU (must read)

When Mysql occupies too much CPU, where should we...

MySQL 8.0.17 installation and configuration graphic tutorial

This article records the graphic tutorial of MySQ...