How to Read a Text File From a Server in Javascript
Read files in JavaScript
How to select files, read file metadata and content, and monitor read progress.
— Updated
Existence able to select and interact with files on the user'south local device is one of the most ordinarily used features of the web. It allows users to select files and upload them to a server, for example, uploading photos, or submitting taxation documents, etc. Merely, it besides allows sites to read and manipulate them without always having to transfer the data beyond the network.
The modern File System Access API #
The File System Access API provides an easy way to both read and write to files and directories on the user'south local organization. It's currently available in most Chromium-derived browsers like Chrome or Edge. To learn more than most information technology, see the File System Access API commodity.
Since the File System Admission API is not compatible with all browsers notwithstanding, cheque out browser-fs-access, a helper library that uses the new API wherever it is available, just falls back to legacy approaches when it is not.
Working with files, the archetype way #
This guide shows y'all how to:
- Select files
- Using the HTML input element
- Using a drag-and-drop zone
- Read file metadata
- Read a file'due south content
Select files #
HTML input element #
The easiest way to allow users to select files is using the <input blazon="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 organization'south born file pick UI. When the user finishes selecting a file or files, the element's change event is fired. Y'all tin can access the list of files from event.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 blazon = "file" id = "file-selector" multiple >
<script >
const fileSelector = certificate. getElementById ( 'file-selector' ) ;
fileSelector. addEventListener ( 'change' , ( event ) => {
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 option UI 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 tin select. For case, an image editing app should only have images, non text files. To do that, you tin can 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-drop #
In some browsers, the <input type="file"> element is also a drop target, assuasive users to drag-and-drop files into your app. Only, the driblet target is pocket-sized, and can be hard to utilize. Instead, once you've provided the core functionality using an <input type="file"> element, you can provide a big, custom drag-and-driblet surface.
Choose your drib zone #
Your drop surface volition depend on the design of your application. You may but want part of the window to be a drib surface, or potentially the unabridged window.
Squoosh allows the user to drag-and-driblet an image anywhere into the window, and clicking select an image invokes the <input type="file"> element. Any you choose as your drop zone, make certain information technology'due south articulate to the user that they can drag-and-drop files onto that surface.
Define the drop zone #
To enable an element to be a elevate-and-drop zone, you'll need to listen for ii events, dragover and drop. The dragover event updates the browser UI to visually indicate that the drag-and-drop action is creating a copy of the file. The drop upshot is fired after the user has dropped the files onto the surface. Like to the input element, y'all can access the list of files from event.dataTransfer.files, which is a FileList object. Each item in the FileList is a File object.
const dropArea = document. getElementById ( 'drop-area' ) ; dropArea. addEventListener ( 'dragover' , ( consequence ) => {
issue. stopPropagation ( ) ;
outcome. preventDefault ( ) ;
// Way the drag-and-drop equally a "copy file" operation.
event.dataTransfer.dropEffect = 'copy' ;
} ) ;
dropArea. addEventListener ( 'drop' , ( upshot ) => {
event. stopPropagation ( ) ;
event. preventDefault ( ) ;
const fileList = upshot.dataTransfer.files;
console. log (fileList) ;
} ) ;
event.stopPropagation() and event.preventDefault() finish the browser'southward 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.
Cheque out Custom drag-and-drop for a live demonstration.
What well-nigh directories? #
Unfortunately, today at that place isn't a good way to go access to a directory.
The webkitdirectory aspect on the <input blazon="file"> element allows the user to cull a directory or directories. Information technology is supported in some Chromium-based browsers, and mayhap desktop Safari, just has conflicting reports of browser compatibility.
If drag-and-drop is enabled, a user may effort to drag a directory into the drib zone. When the drop event is fired, it will include a File object for the directory, but will be unable to access whatsoever of the files within the directory.
The File object contains a number of metadata properties most the file. Most browsers provide the file name, the size of the file, and the MIME type, though depending on the platform, different browsers may provide unlike, or additional information.
function getMetadataForFileList ( fileList ) {
for ( const file of fileList) {
// Not supported in Safari for iOS.
const proper name = file.name ? file.name : 'Non SUPPORTED' ;
// Not 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' ;
console. log ( {file, name, blazon, size} ) ;
}
} Yous can see this in action in the input-type-file Glitch demo.
Read a file'southward content #
To read a file, use FileReader, which enables you to read the content of a File object into retention. You can instruct FileReader to read a file as an array buffer, a data URL, or text.
office readImage ( file ) {
// Check if the file is an image.
if (file.type && !file.blazon. startsWith ( 'image/' ) ) {
console. log ( 'File is not an image.' , file.type, file) ;
render ;
} const reader = new FileReader ( ) ;
reader. addEventListener ( 'load' , ( result ) => {
img.src = event.target.result;
} ) ;
reader. readAsDataURL (file) ;
}
The example above reads a File provided past the user, then converts information technology to a information URL, and uses that data URL to brandish the prototype 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, use the progress consequence 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.event;
// Do something with event
} ) ;
reader. addEventListener ( 'progress' , ( event ) => {
if (event.loaded && event.full) {
const percent = (event.loaded / event.total) * 100 ;
console. log ( ` Progress: ${Math. round (percent) } ` ) ;
}
} ) ;
reader. readAsDataURL (file) ;
} Hero prototype past Vincent Botta from Unsplash
Last updated: — Improve article
Return to all articles
Source: https://web.dev/read-files/
Post a Comment for "How to Read a Text File From a Server in Javascript"