• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 743
  • Last Modified:

Use javascript to check uploaded file type

How to write javascript to check weather the user have uploaded a image file (jpg/gif) before submit
0
yue520
Asked:
yue520
  • 5
  • 4
1 Solution
 
nschaferCommented:
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
 
Pravin AsarCommented:
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
 
yue520Author Commented:
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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Pravin AsarCommented:
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
 
yue520Author Commented:
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
 
yue520Author Commented:
BTW, what I mean was the preview picture thing didn't work on firefox, it only worked on internet explore
0
 
Pravin AsarCommented:


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
 
yue520Author Commented:
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
 
Pravin AsarCommented:
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
 
Pravin AsarCommented:
Firefox would show the local file preview .. i guess because of some security settings...

0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 5
  • 4
Tackle projects and never again get stuck behind a technical roadblock.
Join Now