Solved

File pre-upload check with javascript

Posted on 2010-11-11
11
568 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
0
Comment
Question by:error77
  • 4
  • 3
  • 2
  • +1
11 Comments
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 34116601
0
 

Author Comment

by:error77
ID: 34116649
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
0
 
LVL 29

Expert Comment

by:Badotz
ID: 34116841
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?
0
 
LVL 14

Expert Comment

by:sam2912
ID: 34117478
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)
0
 
LVL 14

Expert Comment

by:sam2912
ID: 34117485
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

0
Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 34118143
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


0
 

Author Comment

by:error77
ID: 34119277
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

0
 
LVL 75

Accepted Solution

by:
Michel Plungjan earned 500 total points
ID: 34119868
Only this
<script>
var acceptType = {'.jpg':1,'.gif':1,'.png':1,'.tif':1,'.jpeg':1,'.mov':1,'.mp4':1,'.flv':1,'.swf':1};
function Ck(val){
  return (val in acceptType);
}
function validate(theForm) {
  var val = theForm.elements["0.file"].value;// assuming file name="0.file"
  if (!Ck(val.substring(val.lastIndexOf('.'))) { 
	  alert(val+' is not allowed. Please choose another file type.');
    return false;
  }
  return true;
}
</script>

Open in new window

0
 

Author Closing Comment

by:error77
ID: 34130629
Thanks
0
 
LVL 29

Expert Comment

by:Badotz
ID: 34130975
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('.')))) {
0
 
LVL 75

Expert Comment

by:Michel Plungjan
ID: 34131063
Thanks
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

In my daily work (mainly using ASP.net), I need to write a lot of JavaScript code. One of the most repetitive tasks I do are the jQuery Ajax calls. You know: (CODE) I don't know if for you it's the same, but for me is soooo tedious to write the …
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
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…

895 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

Need Help in Real-Time?

Connect with top rated Experts

15 Experts available now in Live!

Get 1:1 Help Now