我有要求上传图片并随机生成id存储在数据库中,我无法将其保存在数据库和图像文件夹中。 这是我写的代码,我希望随机生成的id存储在数据库中,图像存储在本地文件夹中
控制器
function add(){
if($this->session->userdata('user_id'))
{
$this->form_validation->set_rules('pp_image','Image','required');
if($this->form_validation->run() == TRUE)
{
if($_FILES["pp_image"]["type"] != "image/jpg" && $_FILES["pp_image"]["type"] != "image/png" && $_FILES["pp_image"]["type"] != "image/jpeg"
&& $_FILES["pp_image"]["type"] != "image/gif" ) {
$this->session->set_flashdata('error','Invalid Image');
redirect('setting/add');
}
$result_data = $this->Home_model->add($_FILES);
if($result_data)
{
$this->session->set_flashdata('success','image Added Successfully');
}
}
else
{
$data['_view'] = 'home/add';
}
}
else{
redirect('admin');
}
}
和这个模型
function add($image){
$image_details = array(
"created_on" => time()
);
$this->db->insert('home',$logo_details);
if(isset($image['pp_image']) && $image['pp_image']['name'] != "")
{
$dir = FCPATH."resources/images/logo/";
if($image["pp_image"]["type"] == "image/jpg" || $image["pp_image"]["type"] == "image/png" || $image["pp_image"]["type"] == "image/jpeg"
|| $image["pp_image"]["type"] == "image/gif" ) {
$hash = md5(rand(1, 1000000).time()).'.jpg';
if(!is_dir($dir))
{
@mkdir($dir, 0777);
}
if(move_uploaded_file($image["pp_image"]["tmp_name"], $dir.$hash))
{
$array['image'] = $hash;
$this->db->update('home',$array);
return TRUE;
}
}
}
return TRUE;
}
这是视图部分
<form role="form" id="logo-form" class="form-horizontal" action="" method="post" enctype="multipart/form-data">
<div class="form-group<?php echo form_error('pp_image') ? "has-error" : "" ?>">
<label class="col-sm-2 control-label" for="form-field-1">
Image :
</label>
<div class="col-sm-9">
<input type="file" name="pp_image">
<?php if (form_error('pp_image')) {
?>
<?php echo form_error('pp_image') ?>
<?php } ?>
</div>
</div>
<div class="col-sm-12">
<input type="submit" value="Submit" class="btn" style="background-color:#16a085; color:white; font-weight:bold;">
</div>
</form>
答案 0 :(得分:0)
首先,表单验证不能仅使用$ _FILES $ _POST。您应该使用CI上传类,这也可以让您更好地验证图像类型。目前,您正在进行两次图像类型验证 - 一次在控制器中,一次在模型中。这可能不是必需的。
将控制器功能更改为:
function add(){
if($this->session->userdata('user_id'))
{
$config['upload_path'] = FCPATH."resources/images/logo/";
$config['allowed_types'] = 'gif|jpg|png';
$config['max_size'] = '100';//eg
$config['max_width'] = '1024';//eg
$config['max_height'] = '768';//eg
$config['file_name'] = $your_random_file_name;
//more config -
$this->upload->initialize($config);
if (!$this->upload->do_upload('pp_image'))
{
$this->session->set_flashdata('error','Invalid Image');
redirect('setting/add');
} else {
//just pass your new filename & path to your model to go in the db
$this->your_model->add($your_random_file_name);
return true;
}
}
}
https://ellislab.com/codeigniter/user-guide/libraries/file_uploading.html