Skip to content Skip to sidebar Skip to footer

Ajax To Php Image Upload

I am attempting to upload multiple images from AJAX to PHP. Here's a run down of what I have so far. HTML
T

Solution 1:

Add id in the file input first, and remember the enctype='multipart/form-data' in form.

<inputclass="images" name="file[]"type="file" multiple>

after that in the script

<script>  
$('YoursubmitbuttonclassorId').click(function() {
var filedata = document.getElementsByName("file"),
        formdata = false;
if (window.FormData) {
    formdata = newFormData();
}
var i = 0, len = filedata.files.length, img, reader, file;

for (; i < len; i++) {
    file = filedata.files[i];

    if (window.FileReader) {
        reader = newFileReader();
        reader.onloadend = function(e) {
            showUploadedItem(e.target.result, file.fileName);
        };
        reader.readAsDataURL(file);
    }
    if (formdata) {
        formdata.append("file", file);
    }
}
if (formdata) {
    $.ajax({
        url: "/path to upload/",
        type: "POST",
        data: formdata,
        processData: false,
        contentType: false,
        success: function(res) {

        },       
        error: function(res) {

         }       
         });
        }
  });
 </script>

In the php file

<?phpfor($i=0; $i<count($_FILES['file']['name']); $i++){
    $target_path = "uploads/";
    $ext = explode('.', basename( $_FILES['file']['name'][$i]));
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1]; 

     if(move_uploaded_file($_FILES['file']['tmp_name'][$i], $target_path)) {
        echo"The file has been uploaded successfully <br />";
     } else{
         echo"There was an error uploading the file, please try again! <br 
     />";
     }
   }
  ?>

Post a Comment for "Ajax To Php Image Upload"