Multiple select and preview of image upload

Posted: April 25, 2014 in Javascripts, Ruby on Rails
Tags: , , ,


<!DOCTYPE html>
<title>File API – FileReader as Data URL</title>
<h1>File API – FileReader</h1>
<label for=”files”>Select multiple files: </label>
<input id=”files” type=”file” multiple/>
<button type=”button” id=”clear”>Clear</button>
<output id=”result” />


window.onload = function(){
//Check File API support
if(window.File && window.FileList && window.FileReader)
$(‘#files’).live(“change”, function(event) {
var files =; //FileList object
var output = document.getElementById(“result”);
for(var i = 0; i< files.length; i++)
var file = files[i];
//Only pics
// if(!file.type.match(‘image’))
if(this.files[0].size < 2097152){
// continue;
var picReader = new FileReader();
var picFile =;
var div = document.createElement(“div”);
div.innerHTML = “<img class=’thumbnail’ src='” + picFile.result + “‘” +
“title=’preview image’/>”;
//Read the image
$(‘#clear, #result’).show();
alert(“Image Size is too big. Minimum size is 2MB.”);
alert(“You can only upload image file.”);

console.log(“Your browser does not support File API”);

$(‘#files’).live(“click”, function() {

$(‘#clear’).live(“click”, function() {



font-family: ‘Segoe UI’;
font-size: 12pt;

header h1{
color: #fff;
background-color: #1BA1E2;
padding: 20px;

width: 80%;


height: 100px;
margin: 10px;
float: left;
#result {
border: 4px dotted #cccccc;
display: none;
float: right;
margin:0 auto;
width: 511px;

The readAsDataURL method is used to starts reading the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains a data: URL representing the file’s data as base64 encoded string.



Multiple select and preview of image upload


Also read:

  1. Arpan says:

    how can i delete the preview images???

  2. How can you make this so if a user is not aware they can upload multiple images at once? As soon as they would go to click upload again the first image is gone. Thank you!

  3. Jaay says:

    now tell us. how to load/store those uploads under d dynamically created folder/directory?

  4. attawit says:

    how can I rename and write to some subdirectory

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s