2

Will work on latest:Chrome Safari Firefox Opera and all versions of IE.
*(client notifications are for demonstration purposes only, and subject to designer decisions and modifications )

Can be used for size and mime-type restrictions.

When mime-type is not an issue, accepting any kind of image format can be done usnig "image" as a function argument.
Multiple mime-types allowed should be separated with the following syntax: "gif|jpeg|png" etc. [see the demo].
Numeric value signifies the maximum size in kilobytes.

Benefits: your client doesn't have to wait until the image uploads on the server just to see that his file is a byte or two bigger than acceptable or of a wrong image type. Reduces wasted bandwidth on wrong content tests and unnecessary server load.
No further scripting required for submit action denial when wrong type/size detected.

Edited by Dani: Fixed formatting

Votes + Comments
nice!
Only just come across this. Wow. Very very nice. Thanks Troy.
<!doctype html>
<html>
<head>
<title>client-side image (type/size) upload validation</title>
<meta charset=utf-8>
<style>
</style>
</head>
<body>

<form><fieldset><legend>Image upload</legend>
<input type=file onchange="getImg(this,500,'jpeg|png')">
</fieldset>
</form>

<script>

function getImg(input,max,accepted){
	var upImg=new Image(),test,size,msg=input.form;
	msg=msg.elements[0].children[0];
	
	return input.files?validate():
	(upImg.src=input.value,upImg.onerror=upImg.onload=validate);

        "author: b.b. Troy III p.a.e";

	function validate(){
		test=(input.files?input.files[0]:upImg);
		size=(test.size||test.fileSize)/1024;
		mime=(test.type||test.mimeType);

	mime.match(RegExp(accepted,'i'))?
	size>max?(input.form.reset(),msg.innerHTML=max+"KB Exceeded!"):
	msg.innerHTML="Upload ready...":	
	(input.form.reset(),msg.innerHTML=accepted+" file type(s) only!")
	}
}

</script> 

</body>
</html>
3
Contributors
4
Replies
64
Views
5 Years
Discussion Span
Last Post by Troy III
0

I don not know your real name but i know that you are a genious programmer, your srcipt works like a charm and solved a big problem for me ,
please note that in line 12 we should use "file" for the input type insted of file.
thanx.

Edited by hamidabbas: error

1

@hamid, No Hamid that's not true.
I was there when quotes were introduced in HTML for the first time in history of the web. They were introduced as allowed means of expressing values which contain "word-break characters".
Meaning, not only they are neither mandatory nor required, they are allowed to be used in a naming tentative which would otherwise break in two or more tokens in case that it required a wbr char.
So, no. Quotes are not required to keep the token in one peace when there are no word breaking characters present. And because this is HTML, not xhtml.

Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.