简体   繁体   中英

multiple image upload validation javascript

I used a php code for multiple file upload. It works well. But, when we click the submit button without uploading any file it shows Success & stored in database as value 0. I tried some javascript validation for "Please upload a Image". But still trying...

Anybody can help me..?

Here is the code...

>   <?php
    if(isset($_FILES['files'])){
     $errors= array();
    foreach($_FILES['files']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['files']['name'][$key];
        $file_size =$_FILES['files']['size'][$key];
        $file_tmp =$_FILES['files']['tmp_name'][$key];
        $file_type=$_FILES['files']['type'][$key];  
        if($file_size > 2097152){
            $errors[]='File size must be less than 2 MB';
        }
        $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) VALUES('$user_id','$file_name','$file_size','$file_type'); ";
        $desired_dir="gallery";
        if(empty($errors)==true){
            if(is_dir($desired_dir)==false){
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }
            if(is_dir("$desired_dir/".$file_name)==false){
                move_uploaded_file($file_tmp,"gallery/".$file_name);
            }else{                                  //rename the file if another one exist
                $new_dir="gallery/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
            mysql_query($query) or die(mysql_error());          
        }else{
                print_r($errors);
        }
     }
    if(empty($error)){
        echo "Success";
    }
    }
    ?>

You could swap if(isset()) with if(!empty()) in the first line to check whether any file has been uploaded.

On client side you could add parameter "required" to <input type=file>

That's my first thought


Id suggest re-writing the script to use Exceptions:

<?php
if(!empty($_FILES['files']))
{

    try
    {

        foreach($_FILES['files']['tmp_name'] as $key => $tmp_name )
        {
            $file_name = $key.$_FILES['files']['name'][$key];
            $file_size =$_FILES['files']['size'][$key];
            $file_tmp =$_FILES['files']['tmp_name'][$key];
            $file_type=$_FILES['files']['type'][$key];

            if($file_size > 2097152)
                throw new Exception('File size must be less than 2 MB');

            $query="INSERT into upload_data (`USER_ID`,`FILE_NAME`,`FILE_SIZE`,`FILE_TYPE`) 
                    VALUES(
                     '". intval($user_id) ."',
                     '". stripslashes(mysql_real_escape_string($file_name)) ."',
                     '". intval($file_size). "',
                     '". stripslashes(mysql_real_escape_string($file_type)) ."'); ";
            $desired_dir="gallery";

            if(is_dir($desired_dir)==false)
            {
                mkdir("$desired_dir", 0700);        // Create directory if it does not exist
            }

            if(is_dir("$desired_dir/".$file_name)==false)
            {
                move_uploaded_file($file_tmp,"gallery/".$file_name);
            }
            else
            {
                //rename the file if another one exist
                $new_dir="gallery/".$file_name.time();
                rename($file_tmp,$new_dir) ;               
            }

            if (!mysql_query($query))
             throw new Exception(mysql_error());
        }

        echo "Success";
    }
    catch (Exception $e)
    {
        print_r($e->getMessage());
    }
}
else
{
    echo "No files uploaded";
}

I tried some javascript validation for "Please upload a Image".

You can add Javascript validation but if your browser support H TML 5 Javascript API - FormData

Javascript

http://jsfiddle.net/dimitardanailov/98VeF/1/

$(document).ready(function() {
  if (window.FormData) {
      $('input[type="file"]').bind({
          change : function()
          {
              var input = this,
              files = input.files;

              if (files.length > 0) {
                  var regExp = new RegExp('image.(jpeg|jpg|gif|png)', 'i');
                  for (var i = 0; i < files.length; i++)
                  {
                      var file = file = files[i];
                      var matcher = regExp.test(file.type);

                      if (!matcher)
                      {
                          alert('invalid file');
                      }
                  }
              } else {
                  alert('please add 1 file');
              }   
          }
      });
  } else {
      alert('Browser not support Formdata');
  }
});
<script type="text/javascript">
    $(function () {
        $('#Image').bind('change', function() {
            var a=(this.files[0].size);
            if((a/1048576) > 2.048) {
                alert('Your file size should not exceed 2 Mb.');
            };
        });
        $('#btnSubmit').click(function () {
            var fileExtension = ['png', 'jpg', 'jpeg'];
            if ($.inArray($(this).val().split('.').pop().toLowerCase(), fileExtension) == -1) {
                alert("Only Png,jpeg and jpg  image files allowed");
                return false;
            }
            else
                return true;
        })
    })
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM