使用CakePHP3将文件/图像上传到数据库

时间:2017-07-22 06:42:45

标签: php mysql cakephp cakephp-3.0

如何使用CakePHP3将图像/文件上传到数据库?我正在创建个人资料页面,用户可以上传他们的个人资料图片。数据库由Images表(id,文件名和图像(BLOB))和Users表组成,它们具有与Images关联的image_id列。以下是我的代码。

Templete档案的一部分

*()

控制器文件

SELECT  
    SUM(INV1.cur_book_bal),
    SUM(inv2.cur_book_bal),
    SUM(INV3.CUR_BOOK_BAL),
    SUM(INV4.CUR_BOOK_BAL)  
FROM
    table1 inv1 
LEFT JOIN
    table1 inv2 ON inv1.CIF_KEY = inv2.CIF_KEY
LEFT JOIN
    table1 inv3 ON inv1.CIF_KEY = inv3.CIF_KEY
LEFT JOIN
    table1 inv4 ON inv1.CIF_KEY = inv4.cif_key
                AND inv1.date = '30-JUN-2014' 
                AND inv2.date = '30-juN-2015' 
                AND INV3.dATE = '30-JUNE-2016' 
                AND INV4.DATE = '30-JUNE-17'

此代码不会将图像保存到数据库。我检查了<?= $this->Form->create($user, ['type' => 'file']) ?> <?= $this->Form->input('image', ['type' => 'file']) ?> <?= $this->Form->button(__('Save')) ?> <?= $this->Form->end() ?> ,它已经

public function edit($id = null)
{
    $user = $this->Users->get($id, ['contain' => ['Images']]);
    if ($this->request->is(['patch', 'post', 'put'])) {
        $data = $this->request->data;
        $user = $this->Users->patchEntity($user, $data);
        if ($data['image']['size'] > 0 && $data['image']['error'] == 0) {
        // Image is uploaded.
            if (!empty($user->image_id)) {
                // Delete old image.
                $old_image = $this->Users->Images->get($user->image_id);
                $this->Users->Images->delete($old_image);
            }
            // Trying to create a new Images entity with $data
            $new_image = $this->Users->Images->newEntity($data['image']);
            $new_image->filename = $data['image']['name'];
            $new_image->image = $data['image’];//This part seems to be incorrect.
            $this->Users->Images->save($new_image)) {
            $user->image = $new_image;
        } else {
            $user->image_id = null;
            $user->image = null;
        }
        if ($this->Users->save($user)) {
            this->Flash->success(__('The user profile has been saved.'));
            return $this->redirect(['action' => 'edit', $user->id]);
        }
        $this->Flash->error(__('The user could not be saved. Please, try again.'));
    }
    $this->set(compact('user'));
    $this->set('_serialize', ['user']);
}

实际图像文件在哪里?如何将其传递给debug($data);{'image' => [ 'name' => 'image_name.png', 'type' => 'image/png', 'tmp_name' => '/tmp/phphmeViC', 'error' => (int) 0, 'size' => (int) 4003 ]} ?我真的很感激任何帮助或评论!提前谢谢!

1 个答案:

答案 0 :(得分:1)

首先,不要在数据库中上传像个人资料图片这样的二进制数据。第二点;只需将图像的文件名和位置存储在DB中。区分您的网站HTML从特定路径加载图像,这对您来说更加轻松。然后,您可以执行:<img src="{$user->profile_image}" />或其他任何操作。

相关问题