MENU
FileReader
FileReader allows you to read the contents of a local file stored on the client's computer.
FileReader |
Inherits: EventTarget |
Constructor: FileReader() |
Properties: DOMError error int readyState = 0:EMPTY 1:LOADING 2:DONE String/ArrayBuffer result |
Methods: void abort() void readAsArrayBuffer(Blob/File data) void readAsBinaryString(Blob/File data) void readAsDataURL(Blob/File data) void readAsText(Blob/File data [, String encoding]) |
Handlers: function(Event e) onabort function(Event e) onerror function(Event e) onload function(Event e) onloadstart function(Event e) onloadend function(Event e) onprogress |
File |
Inherits: Blob (combined below) |
Properties: Date lastModifiedData String name int sizeString type |
Methods: Blob slice([int start [, int end [, String contentType]]]) |
This shows how to preview an image. It also shows how to check the file size and type.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><head><script>
function previewImg(){
var i = document.querySelector('img');
var f = document.querySelector('input[type=file]').files[0];
var r = new FileReader();
if (!f) return;
r.onloadend = function () {i.src = r.result;};
if (f.size>1024*1024) {
alert('The file size must be smaller than 1MB.');
return;
}
if (f.name.substr(-4)!='.jpg'){
alert('The file type must be .jpg.');
return;
}
r.readAsDataURL(f);
}
</script></head><body style="height:400px">
Choose a .jpg file:
<input type="file" onchange="previewImg()"/><br/>
<img/>
</body></html>
This shows how to obtain a file in the browser by dragging it from the outside.
RESETRUNFULL
RESETRUNFULL
<!DOCTYPE html><html><body>
<div style=" border: 10px dashed #ccc; margin: 20px auto; width: 300px; height: 300px;"></div>
<script>
var d = document.querySelector('div');
d.ondragover = function () {return false;};
d.ondrop = function(e) {
this.className = '';
var f = e.dataTransfer.files[0],
r = new FileReader();
r.onload = function (event) {
d.style.background ='url(' + event.target.result + ')';
};
r.readAsDataURL(f);
return false;
};
</script>
</body></html>
Note that there exists a corresponding FileReaderSync interface that allows you to read File or Blob objects synchronously.