HTML and CSS Reference
In-Depth Information
<p>Pick an image file:</p>
<input type="file" id="file_selector" />
<script>
var file_selector = document.getElementById("file_selector");
file_selector.addEventListener("change", function(){
var files_array = this.files;
// we only allowed one file to be selected
if (files_array[0]. type .match(/image/)) { // it's an image file
read_image_file(files_array[0]);
}
}, false);
function read_image_file(file) {
var reader = new FileReader();
reader.onload = function(e){
var image_contents = e.target.result;
var img = document.createElement("img");
img.src = image_contents;
document.body.appendChild(img);
};
reader.readAsDataURL(file);
}
</script>
This code snippet assumes only one file has been selected, but the <input
type="file"> element now supports the multiple attribute, which al-
lows the user to select more than one file at a time. This is why we receive
an array of file references, rather than a single file reference.
If you also want to let the user upload the selected image file, you simply need to send
the file's contents to the server via an XHR Ajax call:
<p>Pick an image file:</p>
<input type="file" id="file_selector" />
<input type="button" id="upload" value="Upload Image" disabled />
<script>
var file_selector = document.getElementById("file_selector");
file_selector.addEventListener("change", function(){
var files_array = this.files;
// we only allowed one file to be selected
if (files_array[0].type.match(/image/)) { // it's an image file
read_image_file(files_array[0]);
file_selector.disabled = true; // disable the file selector now
var upload = document.getElementById("upload");
upload.disabled = false;
upload.addEventListener("click", function(){
upload_file(files_array[0]);
}, false);
}
}, false);
 
Search WWH ::




Custom Search