CodeIgniter - 通过表单上传图像,将图像的位置存储在数据库中

2022-01-09 00:00:00 file upload php mysql codeigniter

我正在尝试通过表单将图像上传到我的网站,但是将图像的位置存储在数据库中(而不是让数据库陷入困境)效率更高.

I'm trying to upload an image to my site through a form, however it's much more efficient to (rather than bog down the database) just store the location of the image in the database.

我的表格有问题,真的不知道该去哪里:

I'm having trouble with my form and really don't know where to go:

<?=form_open('bro/submit_new');?>
 //other form data
 Image: <input type="file" name="image" size="20" /> <br>
 <input type="submit" value="Submit" />
</form>

现在表单本身工作正常,问题是它试图将图像存储到数据库字段图像"(TEXT 类型)中.告诉它只存储文件并将文件位置存储在图像"字段中的最简单方法是什么?(我告诉它通过控制器上传文件的位置).

Now the form itself works fine, the problem is that it's trying to store the image into the database field 'image' (which is type TEXT). What's the easiest way to tell it to just store the file, and give the file location to store in the 'image' field? (I tell it where to upload the file via the controller).

谢谢

控制器代码(本部分):

controller code (for this part):

function submit_new(){
    $config['upload_path'] = './images/';
    $config['allowed_types'] = 'gif|jpg|png';
    $config['max_size'] = '2000';
    $config['max_width']  = '1024';
    $config['max_height']  = '768';     
    $this->load->library('upload', $config);

    $this->db->insert('post', $_POST);

    redirect('bro');
}

推荐答案

CodeIgniter 的文件上传类会帮你搞定.他们的用户指南中的条目解释得很好,所以我要指向你那里.

CodeIgniter's file uploading class will do this for you. The entry in their user guide explains as well as I could, so I'm going to point you there.

基本上你只需要修改他们在那里的控制器,包括一些你将文件 URL 放入数据库的位置,你可以通过使用 $this->upload->data() 并提取[full_path] 从结果数组中提取,然后将其发送到处理数据库输入的模型.

Essentially you'd just need to modify the controller that they have there to include a bit where you put the file URL in the database, which you can accomplish easily by using $this->upload->data() and extracting [full_path] from the resulting array, and then sending it to a model which handles the database input.

相关文章