Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload image using javascript

Tags:

javascript

I'm trying to get image as Object of javascript on the client side to send it using jQuery

<html>
<body>
<script language="JavaScript">
function checkSize()
{
    im = new Image();
    im.src = document.Upload.submitfile.value;
if(!im.src)
    im.src = document.getElementById('submitfile').value;
    alert(im.src);
    alert(im.width);
    alert(im.height);
    alert(im.fileSize);

}
</script>
<form name="Upload" action="#" enctype="multipart/form-data" method="post">
   <p>Filename: <input type="file" name="submitfile" id="submitfile" />
   <input type="button" value="Send" onClick="checkSize();" />
</form>
</body>
</html>

But in this code only alert(im.src) is displaying src of file but alert(im.width),alert(im.height),alert(im.filesize) are not working properly and alerting 0, 0, undefined respectively. Kindly tell me how I can access image object using javascript?

like image 798
Adeel Akram Avatar asked Nov 14 '12 06:11

Adeel Akram


1 Answers

The reason that im.fileSize is only working in IE is because ".fileSize" is only an IE property. Since you have code that works in IE, I would do a check for the browser and render your current code for IE and try something like this for other browsers.

var imgFile = document.getElementById('submitfile');
if (imgFile.files && imgFile.files[0]) {
    var width;
    var height;
    var fileSize;
    var reader = new FileReader();
    reader.onload = function(event) {
        var dataUri = event.target.result,
        img = document.createElement("img");
        img.src = dataUri;
        width = img.width;
        height = img.height;
        fileSize = imgFile.files[0].size;
        alert(width);
        alert(height);
        alert(fileSize);
   };
   reader.onerror = function(event) {
       console.error("File could not be read! Code " + event.target.error.code);
   };
   reader.readAsDataURL(imgFile.files[0]);
}

I haven't tested this code but it should work as long as I don't have some typo. For a better understanding of what I am doing here check out this link.

like image 139
Blake Plumb Avatar answered Oct 17 '22 23:10

Blake Plumb