3

its mine upload html code ;

 <div class="col-xs-12">
    <label for="upload" class="btn btn-sm btn-outline green btn-block">
       <i  class="fa fa-upload"></i>
       upload
   </label><input type="file" multiple id="upload"  class="hidden"/>
 </div>

its file element on change method

 $("#upload").change(function (event) {
            var files = event.target.files;
            files = Object.values(files);
            files.forEach(function (file) {
                if (file.type.match('image')
                    || file.type.match('application/vnd.ms-excel')
                    || file.type.match('application/pdf')
                    || file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                    || file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
                ) {
                    uploadingFile.push(file);
                }
            });
        });

Ajax code when click upload button..

var myFormData = new FormData();
        uploadingFile.forEach(function (file) {
            myFormData.append('myFiles', file);
        });
        myFormData.append('a', 1);
        $.ajax({
            url: 'ajax/upload.php',
            type: 'POST',
            processData: false, // important
            contentType: false, // important
            data: myFormData,success: function(data, textStatus, jqXHR)
            {
              console.log(data);
            }
        });

And Last of code is php code;

    $myFiles=$_FILES["myFiles"];

for($i=0; $i<count($myFiles); $i++){
    $target_path = "uploaded_files/";
    print_r($myFiles[$i]);
    echo $myFiles[$i]["tmp_name"]."\n";
    $ext = explode('.',$myFiles[$i]["tmp_name"]);
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];

    $sonuc=move_uploaded_file($myFiles[$i], $target_path);
    if(move_uploaded_file($myFiles[$i], $target_path)) {
        echo "The file has been uploaded successfully \n";
    } else{
        echo "There was an error uploading the file, please try again! \n";
    }
}

i get this message when run the code. There was an error uploading the file, please try again! I want to upload multiple file to server with array. Why i need an array because I delete some file in array and i want to upload last result of array to server.

What is my fault ? I didn't find anything.

The $myFiles[$i] is a null object.

1
  • Check value of myFormData with console.log before ajax request. Commented Dec 27, 2018 at 8:51

4 Answers 4

6

You are appending single file using this line of code myFormData.append('myFiles', file);. You have to use this code myFormData.append('myFiles[]', file); to send multiple file. Below is the code that i have implemented which can upload multiple files.

in your script place below code.

<script type="text/javascript">
    $("#upload").change(function (event) {
        var files = event.target.files;
        var uploadingFile = [];
        files = Object.values(files);
        files.forEach(function (file) {
            if (file.type.match('image')
                || file.type.match('application/vnd.ms-excel')
                || file.type.match('application/pdf')
                || file.type.match('application/vnd.openxmlformats-officedocument.wordprocessingml.document')
                || file.type.match('application/vnd.openxmlformats-officedocument.presentationml.presentation')
            ) {
                uploadingFile.push(file);
            }
        });

        var myFormData = new FormData();
        uploadingFile.forEach(function (file) {
            myFormData.append('myFiles[]', file);
        });

        $.ajax({
            url: 'upload.php',
            type: 'POST',
            processData: false, // important
            contentType: false, // important
            data: myFormData,success: function(data, textStatus, jqXHR)
            {
              console.log(data);
            }
        });
    });
</script>

And in your upload php code place below code.

$target_path = "uploaded_files/";

$myFiles=$_FILES["myFiles"];
if(count($myFiles['name']) > 1){
    $total = count($myFiles['name']);
    for($i=0; $i<$total; $i++){
        $ext = explode('.',$myFiles["name"][$i]);
        $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];

        if(move_uploaded_file($myFiles["tmp_name"][$i], $target_path)) {
            echo "The file has been uploaded successfully \n";
        } else{
            echo "There was an error multiple uploading the file, please try again! \n";
        }
    }
} else {
    $ext = explode('.',$myFiles["name"]);
    $target_path = $target_path . md5(uniqid()) . "." . $ext[count($ext)-1];

    if(move_uploaded_file($myFiles["tmp_name"], $target_path)) {
        echo "The file has been uploaded successfully \n";
    } else{
        echo "There was an error uploading the file, please try again! \n";
    }
}
Sign up to request clarification or add additional context in comments.

Comments

0

try this

$('body').on('click', '#upload', function(e){
    e.preventDefault();
    var formData = new FormData($(this).parents('form')[0]);

    $.ajax({
        url: 'upload.php',
        type: 'POST',
        xhr: function() {
            var myXhr = $.ajaxSettings.xhr();
            return myXhr;
        },
        success: function (data) {
            alert("Data Uploaded: "+data);
        },
        data: formData,
        cache: false,
        contentType: false,
        processData: false
    });
    return false;

});

Comments

-1
                $("#finalupload").uploadFile({
                       url: "badocumentsupload",
                       id: "test",
                       formData: {
                           action: 'uploadfile',
                           _token: tempcsrf,
                           baid:curaddbaid
                       },
                       fileName: "myfile",
                       returnType: "json",
                       showDelete: true,
                       showDone: false,
                       showProgress: true,
                       onSuccess: function (files, data, xhr) {

                       },
                       deleteCallback: function (data, pd) {
                           $.post("finaluploaddeletecustom", {
                                   action: "delete_current",
                                   row_id: data['DBID'],
                                   filetodelete: data['uploadedfile'],
                                   _token: tempcsrf
                               },
                               function (resp, textStatus, jqXHR) {
                                   reloaddatatable_final();
                               });

                           pd.statusbar.hide();//You choice to hide/not.
                       }
                   });

Comments

-2

As you are getting null object, I don't think that you files are being submitted.I think you have not used enctype="multipart/form-data" in form tag. I think if you add this to form like below, it would work.

<form action="youraction" method="post" enctype="multipart/form-data">

</form>

1 Comment

Don't you see tha OP uploads files with ajax?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.