I am working on an image uploader and I am currently trying to build up an image preview before the upload is done. I have this HTML code:
<input type="file" id="id_imatgeNewPeces"></input><br></br>
<img id="previewing" src="" />
Then I add a listener to the input like this:
document.getElementById('id_imatgeNewPeces').addEventListener('change', this.handleFileSelect, false);
And finally the function handleFileSelect:
handleFileSelect: function(oEvent) {
var file = oEvent.target.files[0];
if (!file.type.match('image.*')) {
sap.m.MessageToast.show("El archivo seleccionado no es una Imagen");
} else {
var readerURL = new FileReader();
readerURL.onload = function() {
$('#previewing').attr('src', readerURL.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
return true;
};
readerURL.readAsDataURL(file);
}
},
I don't know why when I select a file which is not an image it displays the message but when I do select an image when the method onload ends no image is displayed and in addition it seems that the listener has been lost because no further calls are done when if I select another image.
The funny thing is that if I place a breakpoint on line '$('#previewing').attr('height', '230px');' I can see the image but when I continue it disappears. In addition when the method onload ends the fileinput "resets" I mean that it says that it has no selected files.
Besides being a old question, I've found that your code is working as expected:
I just don't undestand why use a native addEventListener() when you are using jquery for DOM manipulation, being easily replaced by:
$("#id_imatgeNewPeces").change(handleFileSelect);
var handleFileSelect = function(oEvent) {
var file = oEvent.target.files[0];
if (!file.type.match('image.*')) {
console.log("El archivo seleccionado no es una Imagen");
} else {
var readerURL = new FileReader();
readerURL.onload = function() {
$('#previewing').attr('src', readerURL.result);
$('#previewing').attr('width', '250px');
$('#previewing').attr('height', '230px');
return true;
};
readerURL.readAsDataURL(file);
}
};
$("#id_imatgeNewPeces").change(handleFileSelect);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="file" id="id_imatgeNewPeces">
<br/><br/>
<img id="previewing" src="" />
Related
I have an array with 3 cells.At the first cell i have a textarea where you can insert the url of an image.At the second cell i have a button which when you click the image display at the third cell where i have a div to display the image.The question is how can i display the image either from the internet either from local?
The code i wrote is:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
mydiv.innerHTML = url.value;
}
<html>
<body>
<input type="text" id="imagename" value="" />
<input type="button" id="btn" value="GO" />
<script type="text/javascript">
document.getElementById('btn').onclick = function() {
img = document.createElement('img');
img.src = document.getElementById('imagename').value;
document.body.appendChild(img);
}
</script>
</body>
</html>
You can see the sample code will add the images from an array to the document.
You could also append the images to any of the elements in your function by using url.appendChild
var arr = ['http://via.placeholder.com/350x150', 'http://via.placeholder.com/350x250','http://via.placeholder.com/350x350']; // hold image urls in an array.
arr.forEach(function(item){
// loop through array and add images to the document.
var img = new Image();
img.src = item;
document.body.appendChild(img);
});
In order to do both you would need to change your html and code.
For the case when the user has a url you can just create a new image and append it to your div setting the image's src to the url that was set in the input:
function loadImage(){
var mydiv = document.getElementById("idofdivtodisplayimg");
var url = document.getElementById("idoftextareawhereyouputtheurl");
var image = new Image;
mydiv.appendChild(image);
image.src = url.value;
}
Now to get it to display a local image you will need a file input or a drag and drop scheme as you cannot access local files without some type of user interaction.
So you would, for example, need to change your html to include a file input, and grab a reference to the selected file the user selects. Then use FileReader to read the file, and finally display it
HTML
<input type="file" id="imagefile">
JS
//input reference
var imageinput = document.getElementById("imagefile");
imageinput.addEventListener('change',function (){
var mydiv = document.getElementById("idofdivtodisplayimg");
var image = new Image;
mydiv.appendChild(image);
//FileReader instance
var reader = new FileReader;
reader.addEventListener('load',function(){
//reader.result will contain a dataURL that can be used
//like a regular image url
image.src = reader.result;
});
//read the file as a dataURL
reader.readAsDataURL( imageinput.files[0] );
});
This does both, it let's you upload an image (or at least load it to the browser) or give a URL to an image source. Click the button and the image is loaded and displayed!
This snippet uses the FileReader API to get the uploaded image and display it in an image element
function uploadOrNot() {
if (document.querySelector("input[type=file]").files[0]){
let input = document.querySelector("input[type=file]");
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
display(e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
} else if (document.querySelector("input[type=text]").value){
display(document.querySelector("input[type=text]").value);
}
}
function display(res) {
let img = document.createElement("IMG");
img.src=res;
document.querySelector("#result").appendChild(img);
}
<div id="urlOrUpload">
<input type="text"/>
<br>
<input type="file" accetp="image/*"/>
</div>
<div id="buttonHolder">
<button type="button" onclick="uploadOrNot()">Display</button>
</div>
<div id="result"></div>
I partly solved it by replacing the div at the third cell with an img tag and at the function i wrote above, i chenged it to:
var image = document.getElementbyId("imageid");
var url = document.getElementbyId("urlid");
image.src = url.value;
But at the table i have,i also have a button where you can add a same row as above.How can i do this function for every url that is placed at every textbox?
I'm working on an app that allows users to post events. I'm using NodeJS, Express and Mongo.
I created a form that allows users to input event details, and upload an image relating to the event. I also created a form that allows the user to edit event details.
The form looks as follows:
The Problem:
User fills form with event details and attaches a picture.
User submits form
User decides he wants to change the event title, but NOTHING ELSE
User clicks edit event, changes the title, and submits
The problem: Even though the user didn't delete the picture associated with the event, the picture is no longer there.
Here is part of my new.ejs file (for posting new event, just adding this here for reference)
<script type="text/javascript" src="/js/eventform.js"></script>
<form action="/events"
method="POST"
enctype="multipart/form-data"
onSubmit="return(validate(this));" // validating user input
novalidate >
....
....
<input name="image" type="file" id="image" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="imageBorder" >
<div id="imageContainer">
<div id="dropbox">
<i class="fa fa-picture-o" aria-hidden="true"></i>
<p> Drop image here or click to upload</p>
</div>
<div id="preview" class="hidden">
</div>
<button id="fileSelect" class="...">Upload Image</button>
<button id="fileRemove" class="...">Remove Image</button>
</div>
</div>
....
....
</form>
Notice that I'm using a hidden input field. Also I have two divs, preview (hidden initially) and dropbox. When an image is uploaded, the class 'hidden' is removed from preview and added to dropbox.
Here is part of the js file newevent.js
$(document).ready(function() {
....
eventImageSetup();
....
}
....
function eventImageSetup() {
var dropbox = document.getElementById("dropbox"),
fileElem = document.getElementById("image"),
fileSelect = document.getElementById("fileSelect"),
fileRemove = document.getElementById("fileRemove");
$(dropbox).height($('#imageBorder').height());
fileSelect.addEventListener("click", function(e) {
if (fileElem) {
fileElem.click();
e.preventDefault(); // to prevent submit
}
}, false);
fileRemove.addEventListener("click", function(e) {
e.preventDefault(); // prevent submit
if(!$('#preview').hasClass('hidden')) { // if there is an image
$('#preview').empty();
$('#dropbox').removeClass('hidden');
$('#preview').addClass('hidden');
$('#fileSelect').text('Upload Image');
$('#image').wrap('<form>').closest('form').get(0).reset();
$('#image').unwrap();
}
removeError($('#imageError'), $('#image'));
});
dropbox.addEventListener("dragenter", dragenter, false);
dropbox.addEventListener("dragover", dragover, false);
dropbox.addEventListener("drop", drop, false);
}
function handleFiles(files) {
var file = files[0];
.... // some error checking
var img = document.createElement("img");
img.id = "uploadedImage";
img.file = file;
img.onload = function() {
adjustImageSize(img);
};
$('#dropbox').addClass('hidden');
$('#preview').removeClass('hidden');
$('#preview').empty();
$('#preview').append(img);
$('#fileSelect').text('Replace Image');
var reader = new FileReader();
reader.onload = (function(aImg) {
return function(e) {
aImg.src = e.target.result;
};
})(img);
reader.readAsDataURL(file);
}
Here is part of my edit.ejs file
<form action="/events/<%=event._id%>?_method=PUT"
method="POST"
enctype="multipart/form-data"
onSubmit="return(validate(this));"
novalidate >
<input name="image" type="file" id="image" accept="image/*" style="display:none" onchange="handleFiles(this.files)">
<div id="imageBorder" >
<div id="imageContainer">
<div id="dropbox" class="hidden">
<i class="fa fa-picture-o" aria-hidden="true"></i>
<p> Drop image here or click to upload</p>
</div>
<div id="preview">
<script>
var imageExists = '<%=event.image%>';
if(imageExists) {
var myImg = document.createElement("IMG");
var source = "../../<%= event.image %>";
myImg.src = source;
adjustImageSize(myImg);
$('#preview').append(myImg);
}
</script>
</div>
<button id="fileSelect" class="...">Upload Image</button>
<button id="fileRemove" class="...">Remove Image</button>
</div>
</div> <!-- END OF imageBorder -->
....
</form>
The script above succesfully makes the image appear in the edit page, as follows.
But when you click submit, the picture doesn't show up.
Here is the nodejs route file. You can see the problem here
// UPDATE SPECIFIC EVENT IN DATABASE
router.put("/:id", upload.single('image'), middleware.checkEventOwnership, function(req, res) {
var filepath = undefined;
if(req.file) {
filepath = req.file.path.substr(7); // Substr to remove "/public"
}
req.body.image = filepath;
Event.findByIdAndUpdate(req.params.id, req.body, function(err, foundEvent) {
if(err) {
console.log(err);
req.flash("error", err);
} else {
req.flash("success", "Successfully edited your event");
}
res.redirect("/events/" + req.params.id);
});
});
Basically, if I leave the image untouched in the edit form, req.file doesn't exist. Thus, req.body.image = undefined. And an image is no longer associated with the event.
Common sense would say do this
if(req.file) {
filepath = req.file.path.substr(7);
req.body.image = filepath;
}
But if you do that, you introduce a new problem: If the user edits the event and removes the image (i.e decides he doesn't want an image associated with the event), the image never gets deleted.
Any idea how to solve this problem? I know I have to do something in the edit.ejs script... More specifically, I need to create an image file... But I'm not sure how to approach this
So I got this to work through a hack I REALLY don't like. I'm sure there is a better, cleaner, standard way of dealing with edit.ejs and images. In other words, please help me find a better solution!
Here are the changes in edit.ejs
<form action="/events/<%=event._id%>?_method=PUT"
method="POST"
enctype="multipart/form-data"
onSubmit="return validate(this) & editPageImageProcessing(this);"
novalidate >
....
....
<div id="preview">
<script>
var imageExists = '<%=event.image%>';
if(imageExists) {
var myImg = document.createElement("IMG");
var source = "../../<%= event.image %>";
myImg.src = source;
myImg.name = "previewImage";
myImg.id = "previewImage";
adjustImageSize(myImg);
$('#preview').append(myImg);
}
</script>
</div>
Basically, I added the lines
myImg.name = "previewImage";
myImg.id = "previewImage";
and added a function editPageImageProcessing.
What this function does is: IF the user didn't upload a new image, and did not delete the image, create a hidden input field "hiddenImage", and let its value be the source of the original image. See below:
// This function deals with edit image
function editPageImageProcessing(form) {
// If the user didn't change the image
// preview would be NOT hidden
// there would not be a req.file (document.getElementById('image').val == '')
// we want a hiddenimage input field
var aFile = document.getElementById('image').value;
console.log("File: ", aFile);
var preview = document.getElementById('preview');
console.log("Preview has hidden class: " + $(preview).hasClass('hidden'));
if(aFile == '' && !$(preview).hasClass('hidden')) {
var input = document.createElement('input');
$(input).attr("name", "hiddenImage");
$(input).attr("id", "hiddenImage");
$(input).attr("type", "hidden");
var myImage = document.getElementById('previewImage');
$(input).attr("value", myImage.src);
$('form').append(input);
}
return true;
}
Now, in the edit route, I did this
// UPDATE SPECIFIC EVENT IN DATABASE
router.put("/:id", upload.single('image'), middleware.checkEventOwnership, function(req, res) {
var filepath = undefined;
if(req.file) { // If user uploaded a new image
filepath = req.file.path.substr(7); // Substr to remove "/public"
console.log(filepath);
} else if(req.body.hiddenImage) { // If user kept the same image
var index = req.body.hiddenImage.lastIndexOf("/uploads");
filepath = req.body.hiddenImage.substr(index);
// req.body.hiddenImage WILL ONLY EXIST if user left image unchanged
}
req.body.image = filepath; // If user deleted image, this will be undefined, which is what we want
Event.findByIdAndUpdate(req.params.id, req.body, function(err, foundEvent) {
if(err) {
console.log(err);
req.flash("error", err);
} else {
req.flash("success", "Successfully edited your event");
}
res.redirect("/events/" + req.params.id);
});
});
Okay, so its messy.
Any better solution would be appreciated
This might seem like a duplicate but please read first and let me know if you have questions. I have a single xpage with two data sources, one form for information and the other for image attachments. Now unlike typical applications I do not want to attach the image to the existing main data source (the first one) I want to asynchronously upload images and create separate documents for each image with the main datasource's UNID as the subID of the new image document. This is the just the way of the current data structure and I have little to no say on changing this so here's the challenge is presented.
I have successfully been able to create xhr requests (with the guide of various async uploader previous works of Julian and Sven) and create new documents with images with the custom control I have written but once I embed it into the XPage with two datasources and attempt to upload and create a new document, it creates a duplicate of the main datasource and wipes out all the other field values (expected behavior of a duplicate with empty fields). I suspect it's because I use the $$submitid and all the required form values for my upload request and they're somehow tied or shared with the first datasource but I can't be too sure.
My custom control has it's own datasource and the xpage has a panel with a datasource as part of it. Custom Control below.
<?xml version="1.0" encoding="UTF-8"?>
<xp:view xmlns:xp="http://www.ibm.com/xsp/core">
<xp:this.data>
<xp:dominoDocument var="imgAttach" formName="mImageAttach"
concurrencyMode="force">
</xp:dominoDocument>
</xp:this.data>
<xp:inputText id="inputText2" style="width:657.0px"><xp:this.defaultValue><![CDATA[#{javascript:facesContext.getExternalContext().getRequest().getRequestURI();
context.getUrl()}]]></xp:this.defaultValue></xp:inputText>
<xp:br></xp:br>
<xp:br></xp:br>
<xp:inputText id="parentId" value="#{imgAttach.ParUNID}"
style="width:333.0px">
<xp:this.defaultValue><![CDATA[#{javascript:var url = context.getUrl().toString();
/*
if(url.indexOf("createComponent.xsp") > 0 && context.getUrlParameter("documentId") != ""){
var doc:NotesDocument = newComponent.getDocument();
return doc.getUniversalID();
} else {
return "";
}
*/}]]></xp:this.defaultValue>
<xp:this.rendered><![CDATA[#{javascript:var url = context.getUrl().toString();
if(url.indexOf("createComponent.xsp") > 0){
return true;
} else {
return false;
}}]]></xp:this.rendered>
</xp:inputText>
<xp:br></xp:br>
<xp:br></xp:br>
<xp:inputText id="inputText1"
defaultValue="#{javascript:imgAttach.getDocument().getUniversalID()}"
style="width:333.0px; display:none;">
</xp:inputText>
<xp:br></xp:br>
<xp:br></xp:br>
<xp:inputText id="Created" style="width:297.0px; display:none;"
value="#{imgAttach.Created}"
defaultValue="#{javascript:#Created()}">
<xp:this.converter>
<xp:convertDateTime type="date" dateStyle="short"></xp:convertDateTime>
</xp:this.converter>
</xp:inputText>
<xp:br></xp:br>
<xp:div styleClass="file-input">
<div class="file-preview ">
<div class="close fileinput-remove">×</div>
<div class="">
<div class="file-preview-thumbnails" id="file-thumbs">
</div>
<div class="clearfix"></div>
<div
class="file-preview-status text-center text-success">
</div>
<div class="fileinput-error file-error-message"
style="display: none;">
</div>
</div>
</div>
<div class="input-group-btn">
<button type="button" tabindex="500"
title="Clear selected files"
class="btn btn-default fileinput-remove fileinput-remove-button">
<i class="glyphicon glyphicon-trash"></i>
Remove
</button>
<button tabindex="500" id="upload-files"
title="Upload selected files"
class="btn btn-default fileinput-upload fileinput-upload-button">
<i class="glyphicon glyphicon-upload"></i>
Upload
</button>
<div tabindex="500" class="btn btn-primary btn-file"
id="files-container">
<i class="glyphicon glyphicon-folder-open"></i>
Browse …
<input name="add-files[0]" id="add-files" type="file"
multiple="true" class="file-input">
</input>
<xp:fileUpload id="FileUploadCtrl"
value="#{imgAttach.Body}" useUploadname="true"
style="display:none">
</xp:fileUpload>
<xp:eventHandler event="onsaveDoc" submit="false"
refreshMode="norefresh" immediate="false" save="true" id="saveDoc" />
</div>
</div>
</xp:div>
<xp:br></xp:br>
<xp:br></xp:br>
<xp:scriptBlock id="scriptBlock2" type="text/javascript">
<xp:this.value>
<![CDATA[
$(function() {
$("#files-container").delegate('input', "change", function() {
var files = !!this.files ? this.files : [];
if (!files.length || !window.FileReader){
//console.log("No file selected or no file reader suppport");
return; // no file selected, or no FileReader support
}
for(i=0; i<files.length; i++) {
if (/^image/.test( files[i].type)){ // only image file
var reader = new FileReader(); // instance of the FileReader
reader.readAsDataURL(files[i]); // read the local file
var img = document.createElement("img");
img.file = files[i];
img.name = 'no_'+ i;
img.classList.add("file-preview-image");
reader.onload = (function(aImg) { return function(e) { aImg.src = e.target.result; }; })(img);
$("#file-thumbs").append(img);
}
}
/*
//add new upload button
var currentInput = $('#add-files');
var nextInput = $('#files-container');
var inputsCount = $('.file-input').length;
// now we change the 'id' attribute of said element because id's should be unique
currentInput.attr('id','add-files'+inputsCount);
// and finally we hide the old element
currentInput.hide();
// now, we append a new input element with an incremented array key defined by the length of already existing input elements
nextInput.append('<input type="file" name="add-files['+inputsCount+']" id="add-files" multiple="true" class="file-input" />');
*/
});
$("#upload-files").on("click", function(e) {
e.preventDefault();
e.stopPropagation();
var all_files = [];
try {
var files = document.querySelectorAll(".file-preview-image");
for(var i = 0; i < files.length; i++) {
//
a_uploader(files[i].file, "#{id:saveDoc}", 0, 10);
}
} catch(e) {
console.log(e);
}
});
function a_uploader(file, uploadID, counter, maxSize){
try {
var formData = new FormData();
formData.append("#{id:FileUploadCtrl}", file);
formData.append("#{id:Created}", document.getElementById("#{id:Created}").value);
formData.append("$$viewid", dojo.query("input[name='$$viewid']")[0].value);
formData.append("$$xspsubmitid", uploadID);
formData.append( "view:_id1", "view:_id1");
if(document.getElementById("#{id:parentId}") != undefined ){
formData.append("#{id:parentId}", document.getElementById("#{id:parentId}").value);
}
var xhr = new XMLHttpRequest();
/* event listners */
xhr.upload.addEventListener("progress", function(e) {
if (e.lengthComputable) {
var percentComplete = Math.round(e.loaded * 100 / e.total);
console.log("Uploading... " +percentComplete.toString() + "%)");
}
else {
console.log("Uploading...")
}
}, false);
xhr.addEventListener("error", function(e) {
//insert error between error div
console.log("error: " + e);
}, false);
xhr.addEventListener("abort", function() {
//insert cancelled between div
console.log("Upload cancelled");
}, false);
xhr.open("PATCH", "#{javascript:context.getUrl()}");
xhr.send(formData);
} catch (e) {
console.log("a_uploader: "+e);
}
}
function clear_inputFiles(){
try {
var files = document.querySelectorAll(".file-preview-image");
for(var i = 0; i < files.length; i++) {
}
} catch(e) {
}
}
});]]>
</xp:this.value>
</xp:scriptBlock>
<xp:this.resources>
<xp:script src="/x$.js" clientSide="true"></xp:script>
</xp:this.resources>
</xp:view>
I thought I had set my first datasource to ignore request params as well as the data source inside of the component control. After setting the ignore request params to true on the first data source and finagling the datasource to get the document ID if it was edit mode, I was then able to use the custom control to upload images independently of the first/main datasource.
Now that they are uploading independently there is still a duplicate being created which seems odd to me. If I click the save button the first data source I don't create any image attachments but if I upload images it creates a duplicate of the primary doc.
Edit:
I had to remove the editDocument and documentId from the URL and specify my own docId as a parameter. I guess the HTTP referrer was the culprit in this case for creating the duplicate....or at least the way the page was set up from creating the doc to saving the doc.
I'm working on an HTML widget which will be embedded in an iBook in iBooks Author for the iPad.
I've got a simple button to trigger image capture on an iPad and all is working fine.
<div id="zeroDiv">
<input type="file" id="getPic" accept="image/*">
</div>
<div id="picWrapper">
<img id="image">
<div id="buttDiv">
<button id="picButt"><span class="buttText">Insert image</span>
</button>
</div>
</div>
and
$('#picButt').click(function () {
$('#getPic').trigger('click');
});
$(document).ready(function () {
$("#getPic").on("change", gotPic);
$("#image").load();
});
function gotPic(event) {
$("#image").attr("src", URL.createObjectURL(event.target.files[0]));
$("#picButt span").text("Change image");
}
fiddle at https://jsfiddle.net/mikawaben/cq2yrh2z/
However, when the user moves off a page and returns, the image is lost as the page reloads. I need to store the image in localStorage.
I know that the fiddle at http://jsfiddle.net/VXdkC/2/ (courtesy of Musa on this site) holds code which could be the key for me.
$('#addNote').click(function () {
var Title = $('#title').val();
var Message = $('#message').val();
var pic = document.getElementById("file").files[0];
var imgUrl;
var reader = new FileReader();
reader.onload = function(e) {
var imgURL = reader.result;
$('#notes').prepend("<div class='entry'><h1>" + Title + "</h1></p>"+ "<p>" + Message + "<img src=" + imgURL + "></p> </div>");
var notes = $('#notes').html();
localStorage.setItem('notes', notes);
saveDataToLocalStorage(imgURL);
}
reader.readAsDataURL(pic);
return false;
});
//show content of notes in storage
$('#notes').html(localStorage.getItem('notes'));
return false;
But despite messing around with it for a couple of hours, I'm not getting it to work. Can anyone lend a hand with this?
I'm also concerned about compression. Do I need to use base64 encoding or something in case the image size causes the whole thing to crash?
Just check to see if there is an imaged saved on page load and display it. Then save the image when selected.
$(document).ready(function () {
$("#getPic").on("change", gotPic);
if (localStorage['url']){
$("#image").attr("src", localStorage['url']);
$("#picButt span").text("Change image");
}
});
function gotPic(event) {
var reader = new FileReader();
reader.onload = function(){
$("#image").attr("src", this.result);
localStorage['url'] = this.result;
$("#picButt span").text("Change image");
}
reader.readAsDataURL(event.target.files[0]);
}
https://jsfiddle.net/cq2yrh2z/1/
I have some code that i changed. It was prevusly to get file ext. I wannted it to get width of uploded image( before even clicking submit input ) and if it's too small giving alert. Problem is that i dont really know how i can connect this js code with html form.
<form id="add" method="POST" enctype="multipart/form-data" action="upload.php">
<input type="file" id= "filput" style="margin-bottom:30px; margin-top:20px;" name="file" size="40" />
</form>
$("#filput").on('change', function () {
var w = $(this).width();
if (w < 500) {
alert("too small");
} else {
alert("big");
}
});
The this referrs to the input not the image. You have too use the HTML5 file API.
You can use this example: How to get the image width from html 5 file API
Code example: copied from: Getting Image Dimensions using Javascript File API
$("#filput").on('change', function () {
var fr = new FileReader;
fr.onload = function() { // file is loaded
var img = new Image;
img.onload = function() {
alert(img.width); // image is loaded; sizes are available
};
img.src = fr.result; // is the data URL because called with readAsDataURL
};
fr.readAsDataURL(this.files[0]); // I'm using a <input type="file"> for demonstrating
});