在CodeIgniter中更新产品图片

时间:2017-11-28 09:52:40

标签: php codeigniter upload codeigniter-3

我尝试制作更新表单,以便用户可以更改产品图片。表单工作正常,除了图片之外,所有内容都会更新。

另外,我有一个product_foto_thumb和一个普通的product_foto,所以我不知道如何在我看来这样做。

我认为这就是我的观点:

<input type="file" name="userfile"/>
<td>
    <?php echo form_input(array('type'=>'hidden','id'=>'product_foto', 'name'=>'product_foto', 'value' => $product['product_foto']));?>
</td>

但我想我还需要product_foto_thumb的输入类型?

这是我的更新控制器功能:

public function update_product() 
{

    $id= $this->input->post('product_id');
    $data = array(
        'product_naam' => $this->input->post('product_naam'),
        'category_id' => $this->input->post('category_id'),
        'ophaal_plaats' => $this->input->post('ophaal_plaats'),
        'product_beschrijving' => $this->input->post('product_beschrijving'),
        'product_foto_thumb' => 'thumb_'.$dataThumb["raw_name"].$dataThumb['file_ext'],
        'product_foto' => 'new_'.$data["raw_name"].$data['file_ext'],
    );
    $this->Update_product_model->update_product_function($id,$data);
}

所以表单有效,但除非我选择新图片并提交表单,否则旧图片将被删除,产品上没有新图片。 任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:0)

试试这段代码,绝对会帮到你。

if($this->input->post('submit')){
    if(($_FILES['userfile'])){
        $errors= array();
        $file_name = $_FILES['userfile']['name'];
        $file_size = $_FILES['userfile']['size'];
        $file_tmp = $_FILES['userfile']['tmp_name'];
        $file_type = $_FILES['userfile']['type'];
        $ext = pathinfo($file_name, PATHINFO_EXTENSION);
        $expensions= array("jpeg","jpg","png");
        // this is used for unique file name always
        $mtime = uniqid(microtime());
        $uniqueid =  substr($mtime,2,8);
        $filename = $uniqueid.'.'.$ext;

        if(in_array($ext,$expensions)=== false){
         $errors[]="extension not allowed, please choose a JPEG or PNG file.";
        }
        if($file_size > 2097152) {
         $errors[]='File size must be excately 2 MB';
        }
        if(empty($errors)==true) {
         move_uploaded_file($file_tmp,"upload_folder_name_here/".$filename);
        }
    }
    $id= $this->input->post('product_id');
    $data = array(
        'product_naam' => $this->input->post('product_naam'),
        'category_id' => $this->input->post('category_id'),
        'ophaal_plaats' => $this->input->post('ophaal_plaats'),
        'product_beschrijving' => $this->input->post('product_beschrijving'),
        'product_foto_thumb' => 'thumb_'.$filename,
        'product_foto' => 'new_'.$filename,
    );
    $this->Update_product_model->update_product_function($id,$data);
}