Php ajax multiple file upload with new array

2019-07-17 06:35发布

问题:

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:

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";
    }
}


回答2:

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;

});



回答3:

                $("#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.
                       }
                   });


回答4:

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>