在代码点火器中为我的文件上传设置值时遇到问题


Having trouble setting value for my file upload in codeigniter

我正在尝试在图像上传输入的输入字段中设置默认值(值表单数据库)。我已经尝试过set_value()它似乎不起作用。我能够获取图像上传输入以外的所有其他字段。

我被困住了,如果可能的话,我将不胜感激,谢谢。

我的观点:

echo form_label('Upload Recipe Image:', 'userfile');    
$valueArray = array(        
    'name' => 'userfile',           
    'value' => $image           
    );      
echo form_upload($valueArray);

控制器功能:

function update_recipe($id) {
        $this->load->model('upload_model');
        $recipe = $this->upload_model->get_recipe($id);
        $config['upload_path'] = './assets/uploads/';
        $config['allowed_types'] = 'gif|jpg|jpeg|png';
        $config['max_size'] = '';
        $config['max_width']  = '600';
        $config['max_height']  = '';
        $config['overwrite'] = TRUE;
        $config['remove_spaces'] = TRUE;
        $this->load->library('upload', $config);
        if(!$this->upload->do_upload()){
            $data['error'] = $this->upload->display_errors('<p>', '</p>');
            $data['user_info'] = $this->model_users->view_user('users')->result();
            $data['recipes'] = $this->recipe_model->get_recipes();
            $this->load->view('includes/header');
            $this->load->view('includes/navigation-header', $data);
            $this->load->view('error', $data);
            $this->load->view('includes/bottom-nav');
            $this->load->view('includes/footer');
        } else {
            $image_data = $this->upload->data();
            $data = array(
                'id'  => $this->input->post('recipe_id'),
                'title' => strtolower($this->input->post('recipe_name')),
                'description' => $this->input->post('recipe_description'),
                'stars' => $this->input->post('rating'),
                'directions' => $this->input->post('recipe_directions'),
                'genre' => $this->input->post('recipe_genre'),
                'posted' =>  date('Y-m-d'),
                'image' => $image_data['file_name'],
                'imagePath' => $image_data['full_path']
            );
            $this->upload_model->update_recipe_form($id, $data);
            redirect('addRecipe/recipes');
        }
    }

你不能那样做。

你的

代码很好,如果你检查你的HTML,你会看到在你的输入元素中设置了该值,但出于安全原因不允许这样做,所以它被忽略了。

想象一下,有人将输入中的动态值设置为 c:''passwords.txt然后通过 javascript 提交表单。钢化文件太容易了。

您在评论中问过:

问题是如果他们想更改标题而不是图像 数据库将更新标题,但将图像替换为空白 田。我将如何解决这个问题?

假设您的update_recipe_form函数等于此函数(来自此 SO 问题):

function update_recipe_form($id, $data){
    $this->db->where('id', $id);
    $this->db->update('recipes', $data);
    return true;
}

基于$this->db->update()函数的描述:

https://ellislab.com/codeigniter/user-guide/database/active_record.html#update

如果从输入数组中排除某些字段,则这些值将不是生成的 SQL 的一部分。

解决方案:尝试检查这些值是否为空:

$image_data['file_name'], $image_data['full_path']

如果为空,则不要将它们包含在 $data 数组中,这样您就不会用空值覆盖现有的数据库值。