Solved

Use javascript to check uploaded file type

Posted on 2006-06-28
10
721 Views
Last Modified: 2008-02-01
How to write javascript to check weather the user have uploaded a image file (jpg/gif) before submit
0
Comment
Question by:yue520
  • 5
  • 4
10 Comments
 
LVL 19

Expert Comment

by:nschafer
Comment Utility
Hi yue520,

When you say have uploaded before submit, do you mean you want to know if they have selected a file in an input type="file" box or do you want to know if they have uploaded a file using a previous form?

Hope this helps,
Neal.
0
 
LVL 28

Expert Comment

by:Pravin Asar
Comment Utility
You may like this one. Has file validation check with preview.


<html>
<HEAD>
<script type="text/javascript">
// valid file types .. Edit ...
var fileTypes=["bmp","gif","png","jpg","jpeg"];

// width to resize large images to
var maxWidth=100;
// height to resize large images to
var maxHeight=100;
// the id of the preview image tag
var outImage="previewField";
// what to display when the image is not valid
var defaultPic="spacer.gif";

function preview(what){
  var source=what.value;
  var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
  for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
  globalPic=new Image();
  if (i<fileTypes.length) globalPic.src=source;
  else {
    globalPic.src=defaultPic;
    alert("THAT IS NOT A FILE EXTENSION\nPlease load an image with an extention of one of the following:\n\n"+fileTypes.join(", "));
  }
  setTimeout("applyChanges()",200);
}
var globalPic;
function applyChanges(){
  var field=document.getElementById(outImage);
  var x=parseInt(globalPic.width);
  var y=parseInt(globalPic.height);
  if (x>maxWidth) {
    y*=maxWidth/x;
    x=maxWidth;
  }
  if (y>maxHeight) {
    x*=maxHeight/y;
    y=maxHeight;
  }
  field.style.display=(x<1 || y<1)?"none":"";
  field.src=globalPic.src;
  field.width=x;
  field.height=y;
}
</script>
</head>


<body>

<div align="center" style="line-height: 1.9em;">
Test it by locating a valid file on your hard drive:
<br>
<input type="file" id="picField" size="40" onchange="preview(this)">
<div style="border: solid black 1; width: 100px; height="100">
<img alt="Graphic will preview here" id="previewField" src="">
<div>
</body>
</html>
0
 

Author Comment

by:yue520
Comment Utility
The uploaded picture doesn't show up on firefox, but it shows fine on explore. Also, I am trying to go to excute.php page when user uploaded a img file, instead on staying on the same page.
0
 
LVL 28

Expert Comment

by:Pravin Asar
Comment Utility
What is shown is a preview, file is not uploaded yet. It is local/


Form submit (action ="" ) has to job of getting the file on server.

0
 

Author Comment

by:yue520
Comment Utility
I have a extra button for user to submit the uploaded picture.

I set a validatePic as true. if the user didn't upload a pic, set validatePic as false.
I made a new function gotoNext() for the button onClick(), I am not sure what went wrong? seems like it didn't do anything?
 

var validatePic = true;

function preview(what){
  var source=what.value;
  var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
  for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
  globalPic=new Image();
  if (i<fileTypes.length) globalPic.src=source;
  else {
    globalPic.src=defaultPic;
    alert("THAT IS NOT A FILE EXTENSION\nPlease load an image with an extention of one of the following:\n\n"+fileTypes.join(", "));
    validatePic = false;
  }
  setTimeout("applyChanges()",200);
}

function gotoNext(validatePic){
      if (validatePic == "true")
      {      
            window.location = "NewTestAction.php";
      }      
      else
      {
            alert("Please upload a correct file");
      }
}


 <h2>Upload and Resize an Image</H2>

    <form method="POST" enctype="multipart/form-data">
          <input type="hidden" name="MAX_FILE_SIZE" value="50000000">

          <p>Upload Image: <input type="file" name="imgfile" id="imgfile" onchange="preview(this)"><br>
          <font size="1">Click browse to upload a local file</font><br>
          <br>
          <input type="button" value="Upload Image" name="submit onClick="javascript: gotoNext();">
    </form>
0
Top 6 Sources for Identifying Threat Actor TTPs

Understanding your enemy is essential. These six sources will help you identify the most popular threat actor tactics, techniques, and procedures (TTPs).

 

Author Comment

by:yue520
Comment Utility
BTW, what I mean was the preview picture thing didn't work on firefox, it only worked on internet explore
0
 
LVL 28

Expert Comment

by:Pravin Asar
Comment Utility


Here is a sample code for you....

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>File Upload</title>
</head>

<body>
<style type="text/css">
TD {
 vertical-align:top;
 text-align:left;
}
</style>
<script type="text/javascript">
// valid file types
var fileTypes=["txt", "bmp","gif","png","jpg","jpeg"];
// width to resize large images to
var maxWidth=100;
// height to resize large images to
var maxHeight=100;
// the id of the preview image tag
var outImage="previewField";
// what to display when the image is not valid
var defaultPic="spacer.gif";

function preview(what){
  var source=what.value;
  var ext=source.substring(source.lastIndexOf(".")+1,source.length).toLowerCase();
  for (var i=0; i<fileTypes.length; i++) if (fileTypes[i]==ext) break;
  globalPic=new Image();
  if (i<fileTypes.length) globalPic.src=source;
  else {
    globalPic.src=defaultPic;
    alert("THAT IS NOT A FILE EXTENSION\nPlease load an image with an extention of one of the following:\n\n"+fileTypes.join(", "));
  }
  setTimeout("applyChanges()",200);
}
var globalPic;
function applyChanges(){
  var field=document.getElementById(outImage);
  field.src=globalPic.src;
  field.style.display = 'block';
}
</script>

<form name="FormUpload" enctype="multipart/form-data" action="upload.php" method="POST">
    <!-- MAX_FILE_SIZE must precede the file input field -->
    <input type="hidden" name="MAX_FILE_SIZE" value="30000" />
    <!-- Name of input element determines name in $_FILES array -->
      <table>
      <tr>
            <td>
                  Files to upload:
            </td>
            <td>
                <input name="userfile[]" size="40" value="" type="file" onchange="preview(this)" />
            <br><input name="userfile[]" size="40" value="" type="file" onchange="preview(this)" />
            <br><input name="userfile[]" size="40" value="" type="file" onchange="preview(this)" />
            <br><input name="userfile[]" size="40" value="" type="file" onchange="preview(this)" />
            <br><input name="userfile[]" size="40" value="" type="file" onchange="preview(this)" />
            </td>
      </tr>
      <tr>
            <td>
                  <input type="reset" value="Reset Form" />      
            </td>
            <td>
                  <input type="submit" value="Send Files" />      
            </td>
      </tr>
      </table>
</form>
<div align="center" style="line-height: 1.9em;">
This is for preview :
<br>
<div style="border: solid black; width: 100px; height:100;">
<img style="display:none;" alt="Graphic will preview here" width="200" id="previewField"  src="">
<div>
</body>
</html>

<!--- PHP CODE  update.php -->
<?php
$uploaddir = './uploads/';
$message = '';

while(list($key,$value) = each($_FILES['userfile']['name']))
{
      if(!empty($value))
      {   // this will check if any blank field is entered
      $filename = $value;    // filename stores the value
      //echo "<br>Uploading file $filename";
      $uploadfile = $uploaddir . $filename;   // upload directory path is set
      if (copy($_FILES['userfile']['tmp_name'][$key], $uploadfile)) {
            $message .= "\nFile $filename is valid, and was successfully uploaded.\n";
               //echo "<br>File $filename is valid, and was successfully uploaded.\n";
      }
      else {
         $message .= "\nPossible file $filename is upload attack! File not uploaded.\n";
         //echo "Possible file $filename is upload attack!<br>File not uploaded.\n";
      }      
      };
};
echo "<pre>$message</pre>";
?>
0
 

Author Comment

by:yue520
Comment Utility
What I want to do was to add a onClick on "sent file" button, so before user submit, it checks for that one file one last time to make sure user was trying to submit a image file.  Also, like what I have mentioned before. the Preview image <img style="display:none;" alt="Graphic will preview here" width="200" id="previewField"  src=""> did NOT work on firefox. it only shows the alt text instead of the image user have try to upload. ( it works ok on internet explore)
0
 
LVL 28

Accepted Solution

by:
Pravin Asar earned 125 total points
Comment Utility
If you want to send one file at a time, you have submit the form ,



About the Preview image <img style="display:none;" alt="Graphic will preview here" width="200" id="previewField"  src=""> did NOT work on firefox.

I did get it.  I will find out more.

Any way, your it is not a requirement, as question says

>>How to write javascript to check weather the user have uploaded a image file (jpg/gif) before submit


So need of shouting it loud. ( in post if your writting something in uppercase letter, ... it is equivalent of shouting.

Good luck to you.

_PA


0
 
LVL 28

Expert Comment

by:Pravin Asar
Comment Utility
Firefox would show the local file preview .. i guess because of some security settings...

0

Featured Post

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

In this article, we'll look how to sort an Array in JavaScript, including the more advanced techniques of sorting a collection of records either ascending or descending on two or more fields. Basic Sorting of Arrays First, let's look at the …
Introduction HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many.  But the PHP code for processing the checkboxes can be confusing at first.  What if a checkbox is…
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…

762 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

10 Experts available now in Live!

Get 1:1 Help Now