client-side Image size/type validation (demo)

Troy III 2 Tallied Votes 3K Views Share

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.

diafol commented: Only just come across this. Wow. Very very nice. Thanks Troy. +15
cereal commented: nice! +13
<!doctype html>
<title>client-side image (type/size) upload validation</title>
<meta charset=utf-8>

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


function getImg(input,max,accepted){
	var upImg=new Image(),test,size,msg=input.form;
	return input.files?validate():

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

	function validate(){

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


Troy III 272 Posting Pro

A working example at jsfiddle

hamidabbas 0 Newbie Poster

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.

KoniKodes 0 Newbie Poster

Thank you so much! I will be referring to this in a future project!

Troy III 272 Posting Pro

@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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.