如何通过jQuery Ajax将两个或多个“输入类型文件”字段上传到数据库?

时间:2019-07-15 07:45:37

标签: javascript php jquery ajax codeigniter-3

视图:

<script>
    $(document).ready(function(){
        $(".vehicle").click(function(e){
            e.preventDefault();
            vehicle_number = $("#vehicle_number").val();

            var fileInputs = $('#dl');
            var formData = new FormData();
            $.each(fileInputs, function(i,fileInput){
                if( fileInput.files.length > 0 )
                {
                    $.each(fileInput.files, function(k,file){
                        formData.append('dl[]', file);
                    });
                }
            });

            var fileInputss = $('#rc');
            var formData = new FormData();
            $.each(fileInputss, function(i,fileInputr){
                if( fileInputr.files.length > 0 )
                {
                    $.each(fileInputr.files, function(k,file){
                        formData.append('rc[]', file);
                    });
                }
            });
            formData.append('vehicle_number', vehicle_number);
            $("#success_vec").html("<img src='<?php echo base_url(); ?>assets/loading.gif'>");
            $.ajax({
                type:"POST",
                data:formData,
                processData: false,
                contentType: false,
                url:"<?php echo base_url(); ?>add_vech",
                success:function(data){
                    $("#success_vec").html(data);
                }
            });

        });
    });
</script>
<form>
    <div id="success_vec"></div>
    <div class="form-row">
        <div class="form-group col-md-6">
            <label for="vehicle_number md-addon">Vehicle Number</label>
            <input type="text" class="form-control" id="vehicle_number">
        </div>
    </div>
    <div class="form-row">
        <div class="form-group col-md-4">
            <label for="dl">Upload DL Of Vehicle Owner</label>
            <input type="file" id="dl">
        </div>
        <div class="form-group col-md-6">
            <label for="rc">Upload RC</label>
            <input type="file" id="rc">
        </div>
    </div>
    <button type="submit" class="btn btn-primary vehicle">save</button>
</form>

控制器:

public function add_vech()
{
    $dataInfo = array();
    $files = $_FILES;
    print_r($files);
}

在这段代码中,我要上传两个文档,即dl and rc。现在,问题是当我同时上载两个字段文件并在控制器内打印该值时,它仅显示最后一个文件数据,即rc。因此,我想知道如何在控制器中打印或上传两个输入文件?请帮助我。

谢谢

1 个答案:

答案 0 :(得分:0)

那是因为您要覆盖formData

var formData = new FormData();

删除formData下的第二个fileInputss实例:

 var fileInputss = $('#rc');
 var formData = new FormData();