【问题标题】:Php ajax multiple file upload with new arrayphp ajax 使用新数组上传多个文件
【发布时间】:2019-05-25 07:09:39
【问题描述】:

我的上传html代码;

 <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>

改变方法的文件元素

 $("#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代码..

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

最后的代码是php代码;

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

我在运行代码时收到此消息。上传文件时出错,请重试!我想用数组将多个文件上传到服务器。为什么我需要一个数组,因为我删除了数组中的一些文件,我想将数组的最后一个结果上传到服务器。

我的错是什么?我什么都没找到。

$myFiles[$i] 是一个空对象。

【问题讨论】:

  • 在 ajax 请求之前检查 myFormDataconsole.log 的值。

标签: php jquery ajax file-upload


【解决方案1】:

您正在使用这行代码myFormData.append('myFiles', file); 附加单个文件。您必须使用此代码myFormData.append('myFiles[]', file); 发送多个文件。下面是我实现的可以上传多个文件的代码。

在代码下方的脚本中。

<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>

并在您上传的 php 代码中放置在代码下方。

$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】:

    试试这个

    $('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】:

        当你得到空对象时,我认为你的文件没有被提交。我认为你没有在表单标签中使用 enctype="multipart/form-data" 。我想如果你把它添加到下面的表格中,它会起作用。

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

        【讨论】:

        • 你没看到 OP 上传文件使用 ajax
        猜你喜欢
        • 2016-05-07
        • 1970-01-01
        • 1970-01-01
        • 2010-12-29
        • 1970-01-01
        • 2012-05-24
        • 2018-11-20
        • 2012-05-04
        • 1970-01-01
        相关资源
        最近更新 更多