Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Use javascript to check uploaded file type

Posted on 2006-06-28
10
Medium Priority
?
741 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 4
10 Comments
 
LVL 19

Expert Comment

by:nschafer
ID: 17004253
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 29

Expert Comment

by:Pravin Asar
ID: 17004298
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
ID: 17012401
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
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!

 
LVL 29

Expert Comment

by:Pravin Asar
ID: 17013005
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
ID: 17013465
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
 

Author Comment

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

Expert Comment

by:Pravin Asar
ID: 17014242


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
ID: 17019232
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 29

Accepted Solution

by:
Pravin Asar earned 375 total points
ID: 17019799
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 29

Expert Comment

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

0

Featured Post

Industry Leaders: 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!

Question has a verified solution.

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

This article discusses the difference between strict equality operator and equality operator in JavaScript. The Need: Because JavaScript performs an implicit type conversion when performing comparisons, we have to take this into account when wri…
Today, the web development industry is booming, and many people consider it to be their vocation. The question you may be asking yourself is – how do I become a web developer?
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…

618 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