我正在尝试上传多张照片!我的代码有效,但仅上传一张照片-并非所有选择的照片。
我的代码有什么问题?
if(count($_FILES["userfile"]["name"]) == 0) {
$this->session->set_flashdata('success', '?? ????? ?????? ?????');
redirect('accidents/index');
}
else {
// configurations from upload library
$config['upload_path'] = './uploads/images';
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$config['max_size'] = '2048000'; // max size in KB
$config['max_width'] = '20000'; //max resolution width
$config['max_height'] = '20000'; //max resolution height
// load CI libarary called upload
$this->load->library('upload', $config);
for($count = 0; $count < count($_FILES["userfile"]["name"]); $count++) {
// body of if clause will be executed when image uploading is failed
if(!$this->upload->do_upload()) {
$errors = array('error' => $this->upload->display_errors());
// This image is uploaded by deafult if the selected image in not uploaded
$image = 'no_image.png';
}
// body of else clause will be executed when image uploading is succeeded
else {
$data = array('upload_data' => $this->upload->data());
$image = $_FILES['userfile']['name']; //name must be userfile
}
$this->accidents_model->addphoto($image,$last_id);
}
}
模型是:
public function addphoto($photo,$last_id) {
$data = array(
'cp_photo' => $photo,
'ac_id' => $last_id
);
//insert image to the database
$this->db->insert('cars_photos', $data);
}
答案 0 :(得分:0)
我在for循环中的代码中发现了问题,它是在重定向到索引页之后上传了一个文件(这是错误的),如果重定向行必须在for循环之外:)
在进行一些修改后,这里有完整的工作代码,能够为每个用户ID创建文件夹(我从堆栈usere中获取代码:)非常感谢)
在我使用的上传页面上
public function upload() {
$acc = $last_id;
$file_path = ".uploads/images/" . $acc . '/';
if (isset($_FILES['multipleUpload'])) {
if (!is_dir('uploads/images/' . $acc)) {
mkdir('.uploads/images/' . $acc, 0777, TRUE);
}
$files = $_FILES;
$cpt = count($_FILES ['multipleUpload'] ['name']);
$this->load->library('upload');
for ($i = 0; $i < $cpt; $i ++) {
$name = $files ['multipleUpload'] ['name'] [$i];
$_FILES ['multipleUpload'] ['name'] = $name;
$_FILES ['multipleUpload'] ['type'] = $files ['multipleUpload'] ['type'] [$i];
$_FILES ['multipleUpload'] ['tmp_name'] = $files ['multipleUpload'] ['tmp_name'] [$i];
$_FILES ['multipleUpload'] ['error'] = $files ['multipleUpload'] ['error'] [$i];
$_FILES ['multipleUpload'] ['size'] = $files ['multipleUpload'] ['size'] [$i];
$this->upload->initialize($this->set_upload_options($file_path));
if(!($this->upload->do_upload('multipleUpload')) || $files ['multipleUpload'] ['error'] [$i] !=0)
{
print_r($this->upload->display_errors());
}
else
{
$this->accidents_model->addphoto($name,$acc);
}
}
//======================================================================================
}
$this->session->set_flashdata('success', 'the files uploaded');
redirect('accidents/index'); // :) here must located outside for loop
}
}
public function set_upload_options($file_path) {
// upload an image options
$config = array();
$config ['upload_path'] = $file_path;
$config ['allowed_types'] = 'gif|jpg|png';
return $config;
}