The FileReader
object lets web applications asynchronously read the contents of files (or raw data buffers) stored on the user's computer, using File or Blob objects to specify the file or data to read. One simple way to access local files is via the <input type="file"/>
HTML form element, that will give you access to readonly.
To check if the browser supports the FileReader API, use the following "if
" statement :
if (window.File && window.FileReader && window.FileList && window.Blob) {
// Read files
} else {
alert('The File APIs are not fully supported by your browser.');
}
A file (or Blob) can be read of different ways with different methods thanks to the FileReader API :
- readAsArrayBuffer.
- readAsBinaryString (non-standard).
- readAsDataURL.
- readAsText.
Every method expects the file as first parameter, to retrieve the file (or files if multiple attribute exists), select the DOM element and retrieve the value of the files property.
var files = document.getElementById("myFileInput").files;
//
var firstOrUniqueFile = files[0];
if(firstOrUniqueFile){
// Do something with the file
}
Note: this value is an array (FileList), therefore you need to access directly the file with the index 0 if the file input is not multiple.
Reading files
As mentioned before, the FileReader allow you to read a file with different methods. Each method treats differently how the content will be returned to you, from plain text to binaryData.
In this article, you'll learn how to use the readAsText
and readAsDataURL
methods properly.
readAsText
The readAsText
method is used to read the contents of the specified File (or Blob). When the read operation is complete, the readyState is changed to DONE
, the loadend is triggered, and the result
attribute of the target contains the contents of the file as a text string.
This method expects as seconds parameter (optional) the codification of the text.
Use the following snippet to get the text content of a file :
<textarea id="editor"></textarea><br>
<p>
Select a file from your computer to being read as text.
</p>
<input type="file" id="filetoRead" />
<script>
document.getElementById("filetoRead").addEventListener("change",function(){
var file = this.files[0];
if (file) {
var reader = new FileReader();
reader.onload = function (evt) {
console.log(evt);
document.getElementById("editor").value = evt.target.result;
};
reader.onerror = function (evt) {
console.error("An error ocurred reading the file",evt);
};
reader.readAsText(file, "UTF-8");
}
},false);
</script>
Test the previous code in the following snippet, it will read the content of a file from your computer without contact any server when you select a file:
readAsDataURL
The readAsDataURL
method is used to read the contents of the specified File (or Blob). When the read operation is finished, the readyState becomes DONE
, and the loadEnd is triggered. At that time, the result attribute of the target contains the data as a
URL representing the file's data as a base64
encoded string.
The following code allow you to read an image from your device and conver it to a base64 string. Then it will be shown in a img tag inside a div :
<div id="image-container">
</div>
<p>
Select an image from your PC to convert it to Base64 and display it in this document
</p>
<input type="file" id="filetoRead" />
<script>document.getElementById("filetoRead").addEventListener("change",function(){
var file = this.files[0];
if (file) {
if ((file.type == 'image/png') ||
(file.type == 'image/jpg') ||
(file.type == 'image/jpeg')
){
var reader = new FileReader();
reader.onload = function (evt) {
var imgTag = '<img style="max-width:300px;" src="'+evt.target.result+'" alt="my image" />';
document.getElementById("image-container").innerHTML = imgTag;
alert("Image succefully loaded");
};
reader.onerror = function (evt) {
console.error("An error ocurred reading the file",evt);
};
reader.readAsDataURL(file);
}else{
alert("Please provide a png or jpg image.");
return false;
}
}
},false);
</script>
Play with the following fiddle and select a file to display it in the browser :
As you can see, it filters only png or jpg images using a simple filter with the mimetype of the file (you can filter according to its extension instead of its mimetype manually). The readAsDataURL can be used, i.e to play an audio file in a video tag.
Have fun