我无法通过ajax上传多个文件。这是我的代码。
HTML代码:
<input type="file" id="txtBusinessImage" class="form-control" name="txtBusinessImageName[]" multiple > <input type="hidden" id="selectBusinessHiddenID" name="selectBusinessHiddenID" value="<?php echo $viewCompanyResult->company_id; ?>"> <input type="button" id="uploadBusinessImg" value="Upload" >
Ajax代码:-
$("#uploadBusinessImg").on("click",function(e) { var fd = new FormData(); var file_data = $("#txtBusinessImage")[0].files; // for multiple files for(var i = 0;i<file_data.length;i++){ fd.append("file"+[i], file_data[i]); } var other_data = $("#selectBusinessHiddenID").serializeArray(); $.each(other_data,function(key,input){ fd.append(input.name,input.value); }); $.ajax({ url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>', data: fd, enctype: 'multipart/form-data', contentType: false, processData: false, type: 'POST', async : true, success: function(data){ alert(data); } }); });
当我通过Ajax调用upload_business_photo_do()函数时,它无法获取图像$ _FILES [‘file’] [‘name’]的名称
upload_business_photo_do() { $business_hidden_id=$this->input->post('selectBusinessHiddenID'); /*code for image*/ $config['upload_path']='./upload_101/'; $config['allowed_types']= 'jpg|png|jpeg'; $config['max_width'] = '6000'; $config['max_height'] = '4500'; $this->load->library('upload',$config); for($i=0; $i<count($_FILES['file']['name']); $i++) { $_FILES['userfile']['name']= $_FILES['file']['name'][$i]; $_FILES['userfile']['type']= $_FILES['file']['type'][$i]; $_FILES['userfile']['tmp_name']= $_FILES['file']['tmp_name'][$i]; $_FILES['userfile']['error']= $_FILES['file']['error'][$i]; $_FILES['userfile']['size']= $_FILES['file']['size'][$i]; if(! $this->upload->do_upload()) { /*----set flash message*/ echo "error"; } else { echo "done"; } } }
尝试这样使用,它简单又容易
$("#uploadBusinessImg").on("click",function(e) { var formData = new FormData($("#form_name")[0]); $.ajax({ url: '<?php echo site_url('Main_ctrl/upload_business_photo_do'); ?>', processData: false, contentType: false, data: formData, type: 'POST', async : true, success: function(data){ alert(data); } }); });
并在控制器中使用像这样
if($_FILES['txtBusinessImageName']) { $file_ary = $this->reArrayFiles($_FILES['txtBusinessImageName']); foreach ($file_ary as $file) { print 'File Name: ' . $file['name']; print 'File Type: ' . $file['type']; print 'File Size: ' . $file['size']; } }
并使用此功能将文件数据转换为多个图像数据的数组
function reArrayFiles(&$file_post) { $file_ary = array(); $file_count = count($file_post['name']); $file_keys = array_keys($file_post); for ($i=0; $i<$file_count; $i++) { foreach ($file_keys as $key) { $file_ary[$i][$key] = $file_post[$key][$i]; } } return $file_ary; }
它的工作完美,只需尝试使用它。您无需使用Ajax添加额外的文件代码。