We help IT Professionals succeed at work.

File pre-upload check with javascript

error77
error77 asked
on
656 Views
Last Modified: 2012-05-10
Hi all,

I need some javascript code that I can use to do the following:

1. Check and restrict what filetype I'm trying to upload
2. Check if I'm trying to submit nothing
3. and check the size and dymentions of image files if possible

I need the javascript to work before or when I click the submit button to upload

Hope someone can help

Thanks
Comment
Watch Question

Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009

Commented:

Author

Commented:
I'm not looking for an upload script. I have one already.

What I'm looking for is some javascript that I can call before it uploads that checks what I'm trying to upload via form input type file.

Hope this helps

thanks
Top Expert 2007

Commented:
Checks what, the file name specified in the element?

You cannot do much with "<input type="file"... />", for good reason. I don't think it can be manipulated in the way you want, but I may be missing something?
CERTIFIED EXPERT

Commented:
Badotz, I think you may be able to get the filename with JavaScript like a normal textbox, but not set it.

TS, to answer your questions:

1) You can only check the extension of the file name, but not the MIME type.
2) This can be done
3) This is not possible until the file has been uploaded to the server. (It only can be done with server-side coding language like PHP)
CERTIFIED EXPERT

Commented:
Example
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>File Field Value</title>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
	$('#button').click(function() {
		alert($('#file').val());
	});
	$('#button2').click(function() {
		$('#file').val("test.html");
	});
});
</script>
</head>

<body>
<form action="" method="get">
	<p>
		<input id="file" type="file" />
	</p>
	<p>
		<input id="button" type="button" value="Show Value of File Field" />
	(This can be done)</p>
	<p>
		<input id="button2" type="button" value="Set Value of File Field" />
	(Proof that this cannot be done)</p>
</form>
</body>
</html>

Open in new window

Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009

Commented:
You are looking for something that can check the size and extension. I posted a script that can do just that. It has settings to do what you want so why write a new one???

Features


    * multiple file select, progress-bar in FF, Chrome, Safari
    * drag-and-drop file select in FF, Chrome
    * uploads are cancellable
    * no external dependencies
    * doesn't use Flash
    * fully working with https
    * keyboard support in FF, Chrome, Safari
    * tested in IE7,8; Firefox 3,3.6,4; Safari4,5; Chrome; Opera10.60;

// validation    
// ex. ['jpg', 'jpeg', 'png', 'gif'] or []
allowedExtensions: [],        
// each file size limit in bytes
// this option isn't supported in all browsers
sizeLimit: 0, // max size  
minSizeLimit: 0, // min size


Author

Commented:
Here is my current code, just in case it can be modified of in case it helps in any way.

See attached

Thanks


<script type="text/javascript">
				function displaymessage()
				{
				alert("Thanks for uploading!");
				}
				</script>
				
				
				<script language="JavaScript" type="text/javascript">
					/*<![CDATA[*/
					function Ck(obj){
					 val=obj.value.substring(obj.value.length-4,obj.value.length);
					 
					 if (val!='.jpg'&&val!='.gif'&&val!='.png'&&val!='.tif'&&val!='.jpeg'&&val!='.mov'&&val!='.mp4'&&val!='.flv'&&val!='.swf'){
					  alert(val+' is not allowed. Please choose another file type.');
					  return false;
					 }
					}
				</script>
				
				<script type="text/javascript">
					function enableSubmitBtn(toShow){
						if(toShow){
							document.getElementById('mySubmit').style.display = "block";
						}else{
							document.getElementById('mySubmit').style.display = "none";
						}
					}
				</script>
				<style type="text/css">
				.hide{
					display:none;
				}
				</style>
				
				<style type="text/css">
				.hide{
					display:none;
				}
				
				input[type=checkbox], input[type=radio] {
    			vertical-align: middle;
   			    position: relative;
   			    bottom: 1px;
  					}
  					input[type=radio] {
    				bottom: 2px;
 					 }

				
				</style>
				
				
				
				
				
				
				
				
				
						<?php
		
													
												
												
													
													echo $form->create('Upload',array('type'=>'file', 'url' => 'uploads','class'=>'form','onSubmit'=>'displaymessage()')); 
													echo $form->input('0.file',array('type'=>'file','label'=>'File Upload:','onchange'=>'Ck(this)'));
													
													echo $form->input('comp_id', array('type'=>'hidden', 'value'=>$c_id));
													
													echo '<div style="padding:10px;">&nbsp;</div>';
													echo '<label><input type="checkbox" id="enableSubmit" onclick="enableSubmitBtn(this.checked);">';
													echo '&nbsp;&nbsp;-&nbsp;&nbsp;<a href="'.$this->webroot.'tac" rel="shadowbox;width=890" style="font-size:100;">I agree to the terms and conditions.</a>';
													echo '</label>';
													
													
													echo '<span class="hide" name="mySubmit" id="mySubmit">';
												
													echo $form->end('Submit');
													echo '</span>';
													
												
		
												?>

Open in new window

IT Expert
CERTIFIED EXPERT
Top Expert 2009
Commented:
This one is on us!
(Get your first solution completely free - no credit card required)
UNLOCK SOLUTION

Author

Commented:
Thanks
Top Expert 2007

Commented:
mplungjan: JSLint does not like your Line 8:

if (!Ck(val.substring(val.lastIndexOf('.'));) {

"Problem at line 8 character 46: Expected ')' and instead saw ';'"

This seems to work:

if (!Ck(val.substring(val.lastIndexOf('.')))) {
Michel PlungjanIT Expert
CERTIFIED EXPERT
Top Expert 2009

Commented:
Thanks

Gain unlimited access to on-demand training courses with an Experts Exchange subscription.

Get Access
Why Experts Exchange?

Experts Exchange always has the answer, or at the least points me in the correct direction! It is like having another employee that is extremely experienced.

Jim Murphy
Programmer at Smart IT Solutions

When asked, what has been your best career decision?

Deciding to stick with EE.

Mohamed Asif
Technical Department Head

Being involved with EE helped me to grow personally and professionally.

Carl Webster
CTP, Sr Infrastructure Consultant
Empower Your Career
Did You Know?

We've partnered with two important charities to provide clean water and computer science education to those who need it most. READ MORE

Ask ANY Question

Connect with Certified Experts to gain insight and support on specific technology challenges including:

  • Troubleshooting
  • Research
  • Professional Opinions
Unlock the solution to this question.
Join our community and discover your potential

Experts Exchange is the only place where you can interact directly with leading experts in the technology field. Become a member today and access the collective knowledge of thousands of technology experts.

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.