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

Reasons and solutions for prompting to save action after uploading files in form

The json data must be returned in html format That...

Detailed tutorial on installing MySQL 8 in CentOS 7

Prepare Environmental information for this articl...

How to build lnmp environment in docker

Create a project directory mkdir php Create the f...

HTML background color gradient effect achieved through CSS style

Effect screenshots: Implementation code: Copy code...

Explanation of MySQL index types Normal, Unique and Full Text

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

Example of how to adapt the Vue project to the large screen

A brief analysis of rem First of all, rem is a CS...

MySQL series multi-table join query 92 and 99 syntax examples detailed tutorial

Table of contents 1. Cartesian product phenomenon...

MySQL and MySQL Workbench Installation Tutorial under Ubuntu

Ubuntu install jdk: [link] Install Eclipse on Ubu...

Pure HTML+CSS to achieve Element loading effect

This is the effect of the Element UI loading comp...

Table paging function implemented by Vue2.0+ElementUI+PageHelper

Preface I have been working on some front-end pro...

A brief talk about Rx responsive programming

Table of contents 1. Observable 2. Higher-order f...