samedi 18 juin 2016

Can't upload multiple files using ajax

First of all this might be a silly question as there are many topics available on this but seriously I am not being able to get it straight and understand how to make it work.

WHAT I AM TRYING TO DO

I am trying to upload multiple files using AJAX and PHP.

PROBLEM

  • I cant figure out how to pass the data to the PHP script using AJAX. I don't want to use a form and a submit button for uploading.
  • Tried using a form and submitting it using jQuery still couldn't make it.

HTML

<div id="content">
    <div id="heading">Upload your files seamlessly</div>
    <a href="#"><div id="upload" class="button" title="Upload your files"><i class="fa fa-cloud-upload fa-align-center" aria-hidden="true"></i>
</div></a>
    <a href="view.php"><div id="view" class="button" title="View all files on my cloud"><i class="fa fa-eye fa-align-center" aria-hidden="true"></i>
</div></a>
</div>

<form id="fileupload" method="POST" enctype="multipart/form-data">
<input type="file" multiple name="uploadfile[]" id="uploadfile" />
</form>

JS

<script type="text/javascript">
$(document).ready(function(){
    $('#upload').click(function(){
        $('input[type=file]').click();
        return false;
    });

    $("#uploadfile").change(function(){
         //submit the form here  
         $('#fileupload').submit();
    });
});
</script>

PHP

<?php
if(isset($_FILES['uploadfile'])){

    $errors= array();

    foreach($_FILES['uploadfile']['tmp_name'] as $key => $tmp_name ){
        $file_name = $key.$_FILES['uploadfile']['name'][$key];
        $file_size =$_FILES['uploadfile']['size'][$key];
        $file_tmp =$_FILES['uploadfile']['tmp_name'][$key];
        $file_type=$_FILES['uploadfile']['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="storage";

        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,"$desired_dir/".$file_name);
            }
            else{                                   // rename the file if another one exist
                $new_dir="$desired_dir/".$file_name.time();
                 rename($file_tmp,$new_dir) ;               
            }
         //mysql_query($query);         
        }
        else{
                print_r($errors);
        }
    }
    if(empty($error)){
        echo "Success";
    }
}
?>

Any help would be appreciated.

Aucun commentaire:

Enregistrer un commentaire