//批量图片处理函数
function multifile_array($upfilename)
{
if(count($_FILES) == 0)
return;
$files = array();
$all_files = $_FILES[$upfilename]['name'];
$i = 0;
foreach ((array)$all_files as $filename) {
$files[++$i]['name'] = $filename;
$files[$i]['type'] = current($_FILES[$upfilename]['type']);
next($_FILES[$upfilename]['type']);
$files[$i]['tmp_name'] = current($_FILES[$upfilename]['tmp_name']);
next($_FILES[$upfilename]['tmp_name']);
$files[$i]['error'] = current($_FILES[$upfilename]['error']);
next($_FILES[$upfilename]['error']);
$files[$i]['size'] = current($_FILES[$upfilename]['size']);
next($_FILES[$upfilename]['size']);
}
$_FILES = $files;
}
//控制器
public function upimgs(){
$cid = intval($this->input->post_get('cid', TRUE));
if(!empty($_FILES['uploadimgs']) && !empty($cid)){
multifile_array('uploadimgs');
$fileNums=count($_FILES);
if($fileNums==0){
header('Location: '.$_SERVER['HTTP_REFERER']);
exit;
}
$curr_upload_dir='course/'.date('Y').'/'.date('m').'/';
$temp_upload_dir=UPLOAD_PATH.$curr_upload_dir;
if(!is_dir($temp_upload_dir)) mkdir($temp_upload_dir, 0755, true);
$upconfig = array(
'upload_path' => $temp_upload_dir,//上传路径
'allowed_types' => 'png|gif|jpg|jpeg|svg||webp',
'max_size' => 2000, //文件大小
'file_ext_tolower' => true, //后缀名小写
'encrypt_name' => true, //生成随机文件名
);
$this->load->library('upload');
$this->upload->initialize($upconfig);// 重点
$batchData=array();
foreach ($_FILES as $file => $file_data){
if($this->upload->do_upload($file)){
$fileinfo = $this->upload->data();
$imgurl='/upload/'.$curr_upload_dir.$fileinfo['file_name'];
$batchData[]=array(
'cid'=>$cid,
'imgurl'=>$imgurl,
'status'=>1,
'sort'=>0,
'addtime'=>time(),
);
}else{
//显示上传错误信息
$err_msg=$this->upload->display_errors();
echo "<script type='text/javascript'>alert('".$err_msg."');history.go(-1);</script>";
exit;
}
}
$this->load->model("CourseImagesModel");
if(!empty($batchData)) $this->CourseImagesModel->insert_batch_data($batchData);
}
header('Location: /courses/imagelist?cid='.$cid);
exit;
}
数据库批量操作模型:
public function insert_batch_data($data) {
return $this->db->insert_batch($this->tablename, $data);
}
html代码:
<table class="table table-bordered">
<form method="post" action="/courses/upimgs" enctype="multipart/form-data">
<tr>
<td style="width: 80%;"></td>
<td><input type="file" name="uploadimgs[]" accept="image/*" class="btn btn-default btn-sm" multiple style="display: inline;"></td>
<td>
<button type="submit" name="submit" value="true" class="btn btn-default">批量上传</button>
</td>
</tr>
</form>
</table>