简体   繁体   English

使用CodeIgniter将图像上传到我的数据库

[英]Uploading an image to my database using CodeIgniter

I know it's wrong to upload images into a db but I need to do it for now. 我知道将图像上传到数据库是错误的,但是我现在需要这样做。

My function looks like this: 我的函数如下所示:

public function runk_image_post()
{
    $id = $this->get('id');
    $imagePath = $_FILES['data']['tmp_name'];

    /// $imagePath = Applications/MAMP/tmp/php/php6cpBhM

    $this->db->trans_start();
    $this->db->query("UPDATE runks SET runk_image = LOAD_FILE('$imagePath') WHERE runk_id='$id';");
    $this->db->trans_complete();

    $query = $this->db->query("SELECT * FROM runks WHERE runk_id = '$id';");
    $message = $query->row();

    if ($this->db->trans_status() === FALSE) {
        $data = ['message' => 'Image not uploaded'];
        $this->response($data, REST_Controller::HTTP_BAD_REQUEST);
    } else {
        $this->response($message, REST_Controller::HTTP_OK);
    }
}

It returns the HTTP_OK response but nothing gets added in the runk_image column (type: blob) in my database. 它返回HTTP_OK响应,但未在数据库的runk_image列(类型:blob)中添加任何内容。 What am I doing wrong? 我究竟做错了什么?

I think it has to do with my $imagePath variable. 我认为这与$ imagePath变量有关。

If you use LOAD_FILE(), you should pass the absolute path of the file. 如果使用LOAD_FILE(),则应传递文件的绝对路径。

EDIT: I do not think LOAD_FILE() should be used (or at least its no good practice) because using it asserts that your web server and the database server have access to the same file system, which is not always the case. 编辑:我不认为应该使用LOAD_FILE()(或至少没有这样做),因为使用它断言您的Web服务器和数据库服务器可以访问同一文件系统,但并非总是如此。

Otherwize you should load the file contents to a variable and pass it as value to your 'runk_image' blob, in this case the code should look as follows: 否则,您应该将文件内容加载到变量中,然后将其作为值传递给“ runk_image” blob,在这种情况下,代码应如下所示:

public function runk_image_post(){
    $id = $this->get('id');
    $imagePath = $_FILES['data']['tmp_name'];

    $imageBin = file_get_contents($imagePath);

    $this->db->trans_start();
    $this->db->where('runk_id', $id);
    $this->db->update('runks',array('runk_image'=>$imageBin));
    $this->db->trans_complete();

    $message = $query->row();

    if ($this->db->trans_status() === FALSE) {
        $data = ['message' => 'Image not uploaded'];
        $this->response($data, REST_Controller::HTTP_BAD_REQUEST);
    } else {
        $this->response($message, REST_Controller::HTTP_OK);
    }}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM