Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What is FileReader in JavaScript

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail what FileReader is in JavaScript. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Foreword:

FileReader is an asynchronous file reading mechanism, which can easily read local files with input:file.

Input:file

Before introducing FileReader, let's briefly introduce the file type of input.

The file type of input is rendered as a button and a piece of text. Click the button to open the file selection window, the text represents the description of the file (in most cases, the file name); the file type input will have the files attribute, which stores the relevant information about the file.

Document.querySelector ('# file') .addEventListener ('change', (fileChoosed) = > {console.log (' fileChoosed', fileChoosed.target.files)})

Click the button to upload a file, and print the uploaded file information on the console, as follows:

You can see that the file information is a json object consisting of an incoming file object. Each file object (that is, each uploaded file) contains the following attributes:

LastModified: a numeric value indicating the number of milliseconds of the last modification time

LastModifiedDate: object that represents the Date object when it was last modified

Name: file name in the local file system

Size: the byte size of the file

Type: string, MIME type of the file

WebkitRelativePath: this is empty; when the webkitdirectory attribute is added to the input, the user can select a folder, where webkitRelativePath represents the relative path of the files in the folder.

FileReader

The above file object only gets the description of the file, but not the data in the file. We can read the data in the file through the FileReader provided by html5.

First create an instance of FileReader:

Const reader = new FileReader ()

FileReader provides the following methods:

ReadAsArrayBuffer (file)

The contents of the file are read in bytes, and the result is represented by an ArrayBuffer object

ReadAsBinaryString (file)

Read the contents of the file in bytes, resulting in a binary string of the file

ReadAsDataURL (file)

Read the contents of the file, and the result is represented as a string of data:url

ReadAsText (file,encoding)

Read the contents of the file by character, and the result is expressed as a string

Abort ()

Terminating a file read operation

ReadAsDataURL and readAsText are commonly used, and only these two are explained here.

ReadAsDataURL will encode the contents of the file with base64 and output them:

Document.querySelector ('# file') .addEventListener ('change', (fileChoosed) = > {const reader = new FileReader (); reader.readAsDataURL (fileChoosed.target.files [0]); / / initiate an asynchronous request reader.onload = function (readRes) {console.log (' load completed', readRes.target.result)}})

The console is the base64-encoded representation of the currently transmitted file. Because the src attribute of the media file can be displayed by using the network address or base64, we can use readAsDataURL to realize the preview of the image.

As follows, you can preview the image simply by assigning the read result to the src attribute of the image:

Document.querySelector ('# file') .addEventListener ('change', (fileChoosed) = > {const reader = new FileReader (); reader.readAsDataURL (fileChoosed.target.files [0]); / / initiate asynchronous request reader.onload = function (readRes) {document.querySelector (' # imgPreview'). Src = readRes.target.result}})

ReadAsText can read the file according to the specified encoding, but the unit to read the file is characters, so for the text file, as long as it is read by the prescribed encoding mode; and for the media file (picture, audio, video), its internal composition is not arranged by characters, so using readAsText to read, will produce garbled code.

FileReader event:

Onloadstart is called when the read operation starts

Onprogress calls periodically during data reading

Called by onabort when a read operation is aborted

Onerror is called when an error occurs in the read operation

Onload is called when the read operation completes successfully.

Onloadend is called when the read operation is complete, regardless of success, failure, or cancellation

Note:

Every time the 50ms passes, a progress event will be triggered. For larger files, you can use progress to implement the progress bar.

The error event is triggered when the file cannot be read for a variety of reasons. When the error event is triggered, the relevant information is stored in the error property of the FileReader object, which stores an object with only one property code, the error code. 1 indicates no file found, 2 indicates security error, 3 indicates read interrupt, 4 indicates unreadable file, and 5 indicates encoding error.

Example:

Document.querySelector ('# file'). AddEventListener ('change', (fileChoosed) = > {const reader = new FileReader (); reader.readAsText (fileChoosed.target.files [0],' utf-8') / / initiate an asynchronous request reader.onloadstart = function (readRes) {/ / cancel loading if (readRes.total > 1024x500) {reader.abort ()} else {console.log ("start loading")} reader.onabort = function (readRes) {console.log if the file is larger than 500kb ('load cancelled')} reader.onprogress = function (readRes) {console.log ("loading" `$ {(readRes.loaded / readRes.total) .tofixed (2) * 100} / 100`)} add: a more comprehensive example

Functions implemented:

Preview text and pictures through the file control

Non-text, output of pictures in binary strings

Drag and drop the above files to achieve the preview

Knowledge points included:

Use of the readAsText method

Use of the readAsDataURL method

Use of the readAsBinaryString method

Some uses of Promise are also interspersed with it.

Simple drag and drop usage

To make it easy to watch, the code is also posted here:

FileReader Learning Select File: (function (window, doc, undefined) {function $(id) {return doc.getElementById (id);} let App = {createFileReader: () = > {if (typeof FileReader = "undefined") {throw new Error ("FileReader is not avaliable") } return new FileReader ();}, / * * @ return FileList * / getFiles: () = > {var attachment = $("attachment"), files = attachment.files; return files | | new Error ("no file uploaded") }, / * * unified read interface * / read: function (api, file, callback) {let self = this; return new Promise ((resolve, reject) = > {let reader = self.createFileReader (); reader.onload = e = > {resolve (e.target.result);} Reader.onerror = e = > {reject ("read error");}; reader.onabort = e = > {reject ("abort error");}; / / size 1 * 1024 * 1024) {reject ('file is too large'); return } reader [api] (file);};}, onFileChange: function (callback) {let self = this; $("attachment"). Onchange = function (e) {callback (self.getFiles ());}, onDrop: function () {let self = this Let resultContainer = $('result'); _ document.ondragover = e = > {e.preventDefault ();}; _ document.ondrop = e = > {e.preventDefault ();}; resultContainer.ondragend = e = > {e.preventDefault ();} ResultContainer.ondrop = e = > {e.preventDefault (); let files = e.dataTransfer.Files; self.handleAll (files);};}, handleFiles: function (files) {let self = this; let p; let ret = [] / / FileList rotation array [] .slice.call (files) .forEach (function (file, I) {const type = file.type; switch (true) {case / text\ /\ w+/.test (type): P = self.read ("readAsText", file); break Case / image\ /\ w+/.test (type): P = self.read ("readAsDataURL", file); break; default: P = self.read ("readAsBinaryString", file); break;} ret.push (p);}); return ret }, init: function () {var self = this; self.onDrop (); / / the onFileChange here cannot be written as Promise, otherwise it will only be valid for the first time, because the state is already fulfilled self.onFileChange (files = > {self.handleAll (files);}) }, handleAll: function (files) {let self = this; Promise.all (self.handleFiles (files)) .then (results = > {self.showResults (results);}) .catch (err = > {console.log (err);}) }, showResults: results = > {console.log (results); let resultContainer = $("result"); results.forEach ((result, I) = > {/ / alert (3); switch (true) {case result.indexOf ("data:image/") > = 0: resultContainer [XSS _ clean] + = `

`; break; default: resultContainer [XSS _ clean] + =`

${result}

`; break;}});}}; App.init ();}) (window, document) This is the end of this article on "what is FileReader in JavaScript?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report