Thursday, October 15, 2009

validating size of the image before uploading with javasript

Here is the code on how to check the size of the image before uploading it to the server using javascript.
First you must create a form...............


<form method="post" action="yourBackEndPath" >

<!-- create the input type file -->
<input type="file" name="inputname" onchange="setImage();" id="fileId">

<!-- create the submit button -->
<input type="submit" value="Upload">

</form>

<!-- create an image tag without any source and make it hidden -->
<img src="" style="display: none;" id="imageSrcId" />

After creating the form create the javascript file size validator...........

// create the function that sets the image
function setImage(){

//get the value of the image from the file

var image = document.getElementById('fileId').value;

//set that value to the image tag
document.getElementById('imageSrcId').src = image;

//call the function that gets the size of the image

setTimeout('getSize()', 10);

}

//create the function that gets the size of the image

function getSize(){

//set the size of the image

var size = document.getElementById('imageSrcId').fileSize;

//now you can see the size of the image that you want to upload

alert('This is the size of the image that I want to upload '+size);


}

If the getSize function doesn't work you can also try this.

//only works on netscape and internet explorer
function getSize(){


if(navigator.appName == "Netscape"){


var image = document.getElementById('imageSrcId');
var size = image.files[0].fileSize;

//heres the size of the image
alert('This is the size of the image '+size);


} else if (navigator.appName == "Microsoft Internet Explorer") {


var size = document.getElementById('imageSample').fileSize;

//heres the size of the image

alert('This is the size of the image '+size);


}

}


There you have it. After you choose the image that you want to save an alert button will show you how the size of the image that you want to upload. Having a knowledge on the size of the image that you want to upload using javascript helps you a lot. You can filter the image that you want to upload in any size that you want before going to the backend. I know that there's a lot of security issues on it but you try that script and filter it again on the server side if you like. Hope this script did help you.

That code was only tested on mozilla firefox and internet explorer.





No comments:

Post a Comment

Feeds

Sonic Run: Internet Search Engine javascript, coldfusion, programming, simple programming teckniques, css, html Webfeed (RSS/ATOM/RDF) submitted to http://www.feeds4all.nl Web Development & Design Blogs DigNow.net

Search Engine Optimization and SEO Tools
javascript, coldfusion, programming, simple programming teckniques, css, html