Read a Text File and Display in Html
Read files in JavaScript
How to select files, read file metadata and content, and monitor read progress.
— Updated
Being able to select and collaborate with files on the user'south local device is 1 of the most commonly used features of the web. It allows users to select files and upload them to a server, for example, uploading photos, or submitting tax documents, etc. But, it too allows sites to read and manipulate them without always having to transfer the information across the network.
The modernistic File Organization Admission API #
The File System Access API provides an easy way to both read and write to files and directories on the user's local system. Information technology's currently available in virtually Chromium-derived browsers like Chrome or Edge. To learn more almost information technology, see the File Organization Access API article.
Since the File Organisation Access API is not compatible with all browsers all the same, check out browser-fs-access, a helper library that uses the new API wherever information technology is bachelor, but falls dorsum to legacy approaches when it is not.
Working with files, the classic way #
This guide shows you lot how to:
- Select files
- Using the HTML input element
- Using a drag-and-drop zone
- Read file metadata
- Read a file's 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, it lets a user select a file, or multiple files if the multiple
aspect is included, using their operating system's born file choice UI. When the user finishes selecting a file or files, the element'due south change
effect is fired. You can admission the list of files from upshot.target.files
, which is a FileList
object. Each particular 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' , ( outcome ) => {
const fileList = event.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 and then logs each selected file to the console.
Limit the types of files user can select #
In some cases, you may want to limit the types of files users can select. For example, an prototype editing app should just accept images, not text files. To practice that, you tin add an accept
attribute to the input chemical element to specify which files are accepted.
<input blazon = "file" id = "file-selector" accept = ".jpg, .jpeg, .png" >
Custom drag-and-driblet #
In some browsers, the <input type="file">
element is also a drop target, allowing users to elevate-and-drop files into your app. But, the drop target is small, and tin be hard to use. Instead, once you've provided the core functionality using an <input type="file">
element, you can provide a large, custom elevate-and-drib surface.
Choose your drop zone #
Your driblet surface will depend on the blueprint of your awarding. You may just want function of the window to exist a driblet surface, or potentially the entire window.

Squoosh allows the user to drag-and-drop an image anywhere into the window, and clicking select an image invokes the <input type="file">
element. Whatever you choose as your driblet zone, make certain it'southward clear to the user that they tin drag-and-driblet files onto that surface.
Define the drop zone #
To enable an element to exist a drag-and-drib zone, y'all'll demand to heed for two events, dragover
and drop
. The dragover
event updates the browser UI to visually point that the drag-and-drop action is creating a re-create of the file. The driblet
event is fired after the user has dropped the files onto the surface. Similar to the input element, you can access the list of files from outcome.dataTransfer.files
, which is a FileList
object. Each particular in the FileList
is a File
object.
const dropArea = document. getElementById ( 'drib-area' ) ; dropArea. addEventListener ( 'dragover' , ( event ) => {
event. stopPropagation ( ) ;
event. preventDefault ( ) ;
// Manner the drag-and-drib as a "copy file" functioning.
issue.dataTransfer.dropEffect = 'copy' ;
} ) ;
dropArea. addEventListener ( 'drop' , ( event ) => {
consequence. stopPropagation ( ) ;
upshot. preventDefault ( ) ;
const fileList = result.dataTransfer.files;
console. log (fileList) ;
} ) ;
outcome.stopPropagation()
and result.preventDefault()
cease the browser'south default behavior from happening, and allow your code 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.
Cheque out Custom elevate-and-drop for a live demonstration.
What about directories? #
Unfortunately, today there isn't a proficient way to get admission to a directory.
The webkitdirectory
attribute on the <input type="file">
element allows the user to cull a directory or directories. It is supported in some Chromium-based browsers, and possibly desktop Safari, just 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 event is fired, information technology will include a File
object for the directory, but will be unable to access whatever of the files inside the directory.
The File
object contains a number of metadata properties well-nigh the file. Most browsers provide the file name, the size of the file, and the MIME type, though depending on the platform, dissimilar browsers may provide different, or boosted information.
function getMetadataForFileList ( fileList ) {
for ( const file of fileList) {
// Not supported in Safari for iOS.
const proper noun = file.proper noun ? file.name : 'NOT SUPPORTED' ;
// Non supported in Firefox for Android or Opera for Android.
const type = file.type ? file.blazon : 'NOT SUPPORTED' ;
// Unknown cross-browser support.
const size = file.size ? file.size : 'Non SUPPORTED' ;
panel. log ( {file, 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, employ FileReader
, which enables you lot to read the content of a File
object into memory. Y'all can instruct FileReader
to read a file as an array buffer, a data URL, or text.
function readImage ( file ) {
// Check if the file is an image.
if (file.type && !file.type. startsWith ( 'epitome/' ) ) {
panel. log ( 'File is not an image.' , file.type, file) ;
return ;
} const reader = new FileReader ( ) ;
reader. addEventListener ( 'load' , ( outcome ) => {
img.src = issue.target.result;
} ) ;
reader. readAsDataURL (file) ;
}
The example above reads a File
provided by the user, then converts it to a information URL, and uses that data URL to display the image in an img
element. Cheque out the read-image-file
Glitch to run into how to verify that the user has selected an paradigm file.
Monitor the progress of a file read #
When reading big files, it may be helpful to provide some UX to bespeak how far the read has progressed. For that, utilise the progress
result provided by FileReader
. The progress
event provides two properties, loaded
, the amount read, and total
, the total amount to read.
function readFile ( file ) {
const reader = new FileReader ( ) ;
reader. addEventListener ( 'load' , ( consequence ) => {
const result = event.target.result;
// Practice something with result
} ) ;
reader. addEventListener ( 'progress' , ( event ) => {
if (outcome.loaded && event.total) {
const percent = (event.loaded / outcome.total) * 100 ;
console. log ( ` Progress: ${Math. round (percent) } ` ) ;
}
} ) ;
reader. readAsDataURL (file) ;
}
Hero prototype by Vincent Botta from Unsplash
Final updated: — Ameliorate commodity
Return to all articles
Source: https://web.dev/read-files/
0 Response to "Read a Text File and Display in Html"
Post a Comment