Solved

How to check file extension?

Posted on 2008-10-16
1
895 Views
Last Modified: 2012-08-14
Hi

I have a jsp page which requires javascript validation of upload file extension

<p class="from"> Picture:                                  
<input type="file" name="myimage">
</p>
<p>
 <input name="submit" type="submit" value="submit">

How to write a javascript to only ALLOW
1) Blank (no browse upload image)
2) .jpg
3) .gif
4) .png
0
Comment
Question by:techques
1 Comment
 
LVL 9

Accepted Solution

by:
Shahzad Fateh Ali earned 50 total points
ID: 22737743
Hi,

Try this. Hope it will work.

Shahzad
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>File Upload</title>
<script language="javascript" type="text/javascript">
	function chkFile(f){
		var v = f.myimage.value;
		if(v.length > 0){
			var ext = getExt(v);
			if(ext === 'jpg' || ext === 'png' || ext === 'gif')
				return true;
			else{
				alert("Invalid Image file");
				return false;
			}
		}else{
			return true;
		}
	}
 
function getExt(v){
	return v.slice(-3);
}
</script>
 
</head>
 
<body>
 
<form name="myform" onsubmit="return chkFile(this)" enctype="multipart/form-data">
	<input type="file" name="myimage" id="myimage" />
	<input type="submit" value="Upload" />
</form>
</body>
</html>

Open in new window

0

Featured Post

Live: Real-Time Solutions, Start Here

Receive instant 1:1 support from technology experts, using our real-time conversation and whiteboard interface. Your first 5 minutes are always free.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

776 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question