Javascript How to Read Content of a File

Read files in JavaScript

How to select files, read file metadata and content, and monitor read progress.

— Updated

Pete LePage

Thomas Steiner

Existence able to select and interact with files on the user's local device is one of the most ordinarily used features of the web. Information technology allows users to select files and upload them to a server, for example, uploading photos, or submitting revenue enhancement documents, etc. But, it also allows sites to read and manipulate them without ever having to transfer the data across the network.

The modern File Organization Access API #

The File System Access API provides an easy fashion to both read and write to files and directories on the user's local system. Information technology'due south currently available in most Chromium-derived browsers similar Chrome or Edge. To learn more well-nigh it, see the File System Access API article.

Since the File System Access API is non compatible with all browsers yet, check out browser-fs-access, a helper library that uses the new API wherever information technology is available, but falls back to legacy approaches when it is not.

Working with files, the classic way #

This guide shows you how to:

  • Select files
    • Using the HTML input chemical element
    • Using a drag-and-drop zone
  • Read file metadata
  • Read a file'south content

Select files #

HTML input element #

The easiest way to allow users to select files is using the <input type="file"> element, which is supported in every major browser. When clicked, information technology lets a user select a file, or multiple files if the multiple attribute is included, using their operating system's built-in file option UI. When the user finishes selecting a file or files, the element's alter event is fired. Y'all can access the listing of files from consequence.target.files, which is a FileList object. Each item in the FileList is a File object.

                          <!-- The `multiple` attribute lets users select multiple files. -->              
<input type = "file" id = "file-selector" multiple >
<script >
const fileSelector = document. getElementById ( 'file-selector' ) ;
fileSelector. addEventListener ( 'change' , ( event ) => {
const fileList = consequence.target.files;
console. log (fileList) ;
} ) ;
</script >

This case lets a user select multiple files using their operating system's built-in file selection UI and then logs each selected file to the console.

Limit the types of files user can select #

In some cases, y'all may want to limit the types of files users tin select. For example, an image editing app should simply accept images, not text files. To do that, you tin add an accept attribute to the input element to specify which files are accepted.

                                                            <input                type                                  =                  "file"                                id                                  =                  "file-selector"                                take                                  =                  ".jpg, .jpeg, .png"                                >                                    

Custom drag-and-drib #

In some browsers, the <input type="file"> element is as well a drib target, assuasive users to elevate-and-drop files into your app. Merely, the driblet target is minor, and tin be hard to use. Instead, once you've provided the core functionality using an <input type="file"> chemical element, you lot can provide a large, custom drag-and-drop surface.

Choose your drop zone #

Your drop surface will depend on the pattern of your application. You may simply desire part of the window to be a driblet surface, or potentially the entire window.

A screenshot of Squoosh, an image compression web app.
Squoosh makes the unabridged window a drop zone.

Squoosh allows the user to drag-and-driblet an paradigm anywhere into the window, and clicking select an image invokes the <input blazon="file"> chemical element. Any you choose every bit your drib zone, make sure information technology's clear to the user that they can drag-and-drop files onto that surface.

Define the drop zone #

To enable an element to be a drag-and-drop zone, you'll need to heed for two events, dragover and drop. The dragover event updates the browser UI to visually signal that the drag-and-drop activity is creating a copy of the file. The drop outcome is fired after the user has dropped the files onto the surface. Similar to the input element, y'all tin can access the list of files from upshot.dataTransfer.files, which is a FileList object. Each item in the FileList is a File object.

                          const              dropArea              =              document.              getElementById              (              'drop-expanse'              )              ;              

dropArea. addEventListener ( 'dragover' , ( consequence ) => {
event. stopPropagation ( ) ;
event. preventDefault ( ) ;
// Mode the drag-and-drop equally a "re-create file" functioning.
event.dataTransfer.dropEffect = 'copy' ;
} ) ;

dropArea. addEventListener ( 'drop' , ( event ) => {
event. stopPropagation ( ) ;
event. preventDefault ( ) ;
const fileList = upshot.dataTransfer.files;
panel. log (fileList) ;
} ) ;

consequence.stopPropagation() and event.preventDefault() end the browser's default beliefs from happening, and allow your lawmaking to run instead. Without them, the browser would otherwise navigate away from your page and open the files the user dropped into the browser window.

Check out Custom drag-and-drib for a alive sit-in.

What about directories? #

Unfortunately, today in that location isn't a good way to get access to a directory.

The webkitdirectory attribute on the <input type="file"> element allows the user to choose a directory or directories. It is supported in some Chromium-based browsers, and possibly desktop Safari, but has conflicting reports of browser compatibility.

If drag-and-drop is enabled, a user may try to drag a directory into the drop zone. When the drop issue is fired, information technology will include a File object for the directory, only will be unable to access any of the files within the directory.

The File object contains a number of metadata properties about the file. Most browsers provide the file name, the size of the file, and the MIME blazon, though depending on the platform, unlike browsers may provide dissimilar, or additional information.

                          function              getMetadataForFileList              (              fileList              )              {              
for ( const file of fileList) {
// Not supported in Safari for iOS.
const name = file.name ? file.name : 'Non SUPPORTED' ;
// Non supported in Firefox for Android or Opera for Android.
const type = file.type ? file.type : 'NOT SUPPORTED' ;
// Unknown cantankerous-browser back up.
const size = file.size ? file.size : 'NOT SUPPORTED' ;
panel. log ( {file, proper name, type, size} ) ;
}
}

You can see this in action in the input-type-file Glitch demo.

Read a file's content #

To read a file, use FileReader, which enables y'all to read the content of a File object into memory. Yous can instruct FileReader to read a file as an array buffer, a information URL, or text.

                          part              readImage              (              file              )              {              
// Check if the file is an image.
if (file.type && !file.type. startsWith ( 'image/' ) ) {
console. log ( 'File is non an epitome.' , file.type, file) ;
return ;
}

const reader = new FileReader ( ) ;
reader. addEventListener ( 'load' , ( event ) => {
img.src = event.target.result;
} ) ;
reader. readAsDataURL (file) ;
}

The case above reads a File provided by the user, then converts it to a data URL, and uses that data URL to display the image in an img element. Check out the read-image-file Glitch to see how to verify that the user has selected an image file.

Monitor the progress of a file read #

When reading large files, it may be helpful to provide some UX to indicate how far the read has progressed. For that, apply the progress event provided past FileReader. The progress event provides two properties, loaded, the amount read, and full, the total amount to read.

                                          function                readFile                (                file                )                {                            
const reader = new FileReader ( ) ;
reader. addEventListener ( 'load' , ( event ) => {
const result = consequence.target.result;
// Exercise something with issue
} ) ;

reader. addEventListener ( 'progress' , ( consequence ) => {
if (event.loaded && event.total) {
const percent = (event.loaded / consequence.total) * 100 ;
console. log ( ` Progress: ${Math. round (percent) } ` ) ;
}
} ) ;
reader. readAsDataURL (file) ;
}

Hero prototype past Vincent Botta from Unsplash

Last updated: — Ameliorate article

Return to all articles

guzmanmarreird.blogspot.com

Source: https://web.dev/read-files/#:~:text=To%20read%20a%20file%2C%20use,a%20data%20URL%2C%20or%20text.

0 Response to "Javascript How to Read Content of a File"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel