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 use cases of MySql escape

MySQL escape Escape means the original semantics ...

Several practical scenarios for implementing the replace function in MySQL

REPLACE Syntax REPLACE(String,from_str,to_str) Th...

How to set up virtual directories and configure virtual paths in Tomcat 7.0

Tomcat7.0 sets virtual directory (1) Currently, o...

How to use provide to implement state management in Vue3

Table of contents Preface How to implement Vuex f...

Detailed tutorial on using the Prettier Code plugin in vscode

Why use prettier? In large companies, front-end d...

Detailed tutorial on installing and configuring MySql5.7 on Ubuntu 20.04

Table of contents 1. Ubuntu source change 2. Inst...

Use Docker to build a Git image using the clone repository

Overview I have been using Docker for more than a...

Example of using Nginx reverse proxy to go-fastdfs

background go-fastdfs is a distributed file syste...

Implementation steps of vue-element-admin to build a backend management system

Recently, when I was working on a conference heal...

In-depth understanding of slot-scope in Vue (suitable for beginners)

There are already many articles about slot-scope ...

Docker win ping fails container avoidance guide

Using win docker-desktop, I want to connect to co...