使用 jQuery AJAX 形式和其他数据上传 Dropzone 文件

Upload Dropzone files using a jQuery AJAX form with other data

在我的项目中,注册用户应该能够通过 jQuery AJAX 表单添加新闻,同时他可以 select 并上传将附加的多张图片到 post.

我正在使用 Codeigniter 3,jQuery 并且我正在尝试将 Dropzone 添加到 select 并预览图片。 我的目标是将 Dropzone selected 文件附加到 jQuery AJAX 表单并在单击提交按钮时发送文件和数据。

到目前为止,jQuery 表单可以正常发送文本数据,代码如下:

$('#news_form').on("submit",function(e){
    e.preventDefault();
    var form_action = `${HOST_URL}/news/add_post`;
    var fdata = new FormData(this);
    fdata.append(token_name, token_hash);
    fdata.append('file', $('#file_dropzone')[0].dropzone.getAcceptedFiles()[0]);
    
    $.ajax({
        url: form_action,
        type: 'POST',
        data: fdata,
        processData:false,
        contentType: false,
        cache: false,
        dataType:'json',
    })
    .done(function(data){            
        if(data.status){
            $("#news_form")[0].reset();
            $( ".telegram_input" ).prop( "disabled", true );
            toastr.success(data.toastmsg, 'Success!', {timeOut: 5000});
        }else{   
            toastr.error(data.toastmsg, 'Error!', {timeOut: 5000});
        }
    })
    .fail(function(data) {
        toastr.error(data.toastmsg, 'Error!', {timeOut: 5000});
    })
    .always(function(data) {
        token_hash = data.csrf_test_name;
    });
});

在上面的代码中,我添加了具有以下行的 Dropzone selected 文件:

fdata.append('files', $('#file_dropzone')[0].dropzone.getAcceptedFiles()[0]);

要初始化 Dropboz 区域,我使用以下代码:

"use strict";
var LIDBDropzone = function () {
    // Private functions
    var dropfile = function () {
        Dropzone.autoDiscover = false;

        var myDropzone = new Dropzone(".dropzone", {
            url: '',
            autoProcessQueue: false,
            paramName: "files",
            maxFilesize: 1,
            maxFiles: 5,
            acceptedFiles: ".jpeg,.jpg,.png",
            parallelUploads:10,
            uploadMultiple:true,
        });
    }

    return {
        init: function() {
            dropfile();
        }
    };
}();

KTUtil.ready(function() {
    LIDBDropzone.init();
});

Dropzone HTML 代码如下:

<div class="dropzone dropzone-default dropzone-primary" id="file_dropzone">
    <div class="dropzone-msg dz-message needsclick">
        <h3 class="dropzone-msg-title">Drop files here or click to upload.</h3>
        <span class="dropzone-msg-desc">Upload up to 10 files</span>
    </div>
</div>

当我尝试发送表单时出现问题,数据和文件由下面的 Codeigniter 函数处理:

# Count uploaded files
$countfiles = count($_FILES['files']['name']);

# Do the dirt job ... upload all the pictures
for($i=0;$i<$countfiles;$i++)
{               
    if(!empty($_FILES['files']['name'][$i]))
    {
        // Define new $_FILES array - $_FILES['file']
        $_FILES['file']['name'] = $_FILES['files']['name'][$i];
        $_FILES['file']['type'] = $_FILES['files']['type'][$i];
        $_FILES['file']['tmp_name'] = $_FILES['files']['tmp_name'][$i];
        $_FILES['file']['error'] = $_FILES['files']['error'][$i];
        $_FILES['file']['size'] = $_FILES['files']['size'][$i];
        
        # Load and configure upload library
        $this->load->library('upload');
        $config = array(
                'upload_path'      => $upload_path,
                'allowed_types'    => 'jpg|png',
                'max_size'         => '250', // 250Kb
                'max_width'        => '1400',
                'max_height'       => '1200',
                //'file_name'        => $filename,
                'encrypt_name'     => TRUE,
                'overwrite'        => false,
                'file_ext_tolower' => true
                );
        $this->upload->initialize($config);
                    
        # Upload each file
        if (!$this->upload->do_upload('file'))
        {
            $jsondata['status'] = FALSE;
            $jsondata['error'] = TRUE;
            $jsondata['toastmsg'] = $this->upload->display_errors();
            die(json_encode($jsondata));
        }

        $data = $this->upload->data(); 
        
        $picture = $data['file_name'];
        # End upload
    }
}

我得到的错误如下:

A PHP Error was encountered
Severity: Warning

Message: count(): Parameter must be an array or an object that implements Countable

所以似乎没有文件传递给 PHP 代码。

问题是:

非常感谢您的帮助

您应该计算超级全局 $_FILES['files'] 中的元素(文件),这将为您提供上传文件的数量,而不是 $_FILES['files']['name']