How to Read From a File With Html
JavaScript read File Reading local files with JavaScript
This is a repost from my weblog
For security and privacy reasons spider web apps practise not have directly access to the files
on the user'southward device. If you demand to read one or multiple local files, y'all can do
this through the usage of a file input and a FileReader. In this post we will have a look
at how this works through a few examples.
TL;DR
- JavaScript does not have direct admission to the local files due to security and privacy.
- We can offer the user the possibility to select files via a
file
input element that we can and so process. - The
file
input has afiles
property with the selected file(s). - We can utilize a
FileReader
to access the content of the selected file(s).
How it works
As JavaScript in the browser cannot access the local files from the user'south device,
we demand to provide the user with a way to select one or multiple files for u.s.a. to use.
This can be done with the HTML file input element:
<input type= "file" id= "fileInput" >
If nosotros desire to allow the selection of multiple files, we tin add together the multiple
attribute:
<input type= "file" id= "fileInput" multiple >
We tin either utilize the alter
event of the input field to respond to a file selection
or add some other UI chemical element to let the user explicitly start the processing of the selected file.
Also note: The selection of a file with the input element does not upload the file anywhere,
the simply thing that happens is that the file becomes bachelor to the JavaScript on the page.
The file input has a files
property that is a list (as at that place could exist multiple selected files) of File
objects.
<input type= "file" id= "fileInput" > <script> document . getElementById ( ' fileInput ' ). addEventListener ( ' change ' , function selectedFileChanged () { console . log ( this . files ); // will contain information nigh the file that was selected. }); </script>
A File
object looks like this:
{ name : ' test.txt ' , // the proper name of the selected file size : 1024 , // the size in bytes type : ' text/plain ' , // the assumed file type based on file extension. This might be incorrect. lastModified : 1234567890 , // timestamp of the last change according to the user's organisation lastModifiedDate : ' Thu Jul 04 2019 09:22:51 GMT+0200 (Central European Summer Time) ' // a engagement object for the final modified timestamp }
Now we have the ability to select a file and see the metadata, but how can nosotros admission the file content?
To go the actual content of a selected file, we demand a FileReader
.
A file reader takes a File
object and offers u.s. methods to become access to the information as:
- a cord of text data
- a data URL
- a string of binary data
- an ArrayBuffer containing raw binary data
In the post-obit examples, we will employ the readAsText
and readAsDataURL
methods to show the content of text and prototype files.
Instance one: Reading text files
To show the file content equally text, we change the change
event handler:
document . getElementById ( ' fileInput ' ). addEventListener ( ' change ' , function selectedFileChanged () { if ( this . files . length === 0 ) { console . log ( ' No file selected. ' ); return ; } const reader = new FileReader (); reader . onload = function fileReadCompleted () { // when the reader is done, the content is in reader.event. console . log ( reader . result ); }; reader . readAsText ( this . files [ 0 ]); });
First we brand sure that there is a file that can exist read. If the user cancels or otherwise
closes the file selection dialog without selecting a file, we have aught to read and go out our function.
Nosotros and so proceed to create a FileReader
. The reader works asychronously in order
to not cake the main thread and UI updates which is of import when reading large files (like videos).
The reader emits a 'load' event (similar to images for case) that tells our code that the reading is finished.
The reader keeps the file content in its issue
belongings. The data in this property depends on which method we used to read the file.
In our example we read the file with the readAsText
method, and then the result
will be a string of text.
Example two: Displaying an image from the user's device
If we desire to display images, reading the file into a string isn't very helpful.
Conveniently the FileReader
has a readAsDataURL
method that reads the file into
an encoded string that can be used as the source for an <img>
element. The lawmaking is pretty much the aforementioned as previously,
with the exceptions that we read the file with readAsDataURL
and display the result as an image:
document . getElementById ( ' fileInput ' ). addEventListener ( ' change ' , function selectedFileChanged () { if ( this . files . length === 0 ) { console . log ( ' No file selected. ' ); return ; } const reader = new FileReader (); reader . onload = role fileReadCompleted () { const img = new Prototype (); // creates an <img> element img . src = reader . consequence ; // loads the data URL as the image source document . body . appendChild ( img ); // adds the prototype to the body }; reader . readAsDataURL ( this . files [ 0 ]); });
Source: https://dev.to/g33konaut/reading-local-files-with-javascript-25hn
0 Response to "How to Read From a File With Html"
Post a Comment