gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 23:12:40 24 4
gpt4 key购买 nike

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

Templete文件的一部分

<?= $this->Form->create($user, ['type' => 'file']) ?>
<?= $this->Form->input('image', ['type' => 'file']) ?>
<?= $this->Form->button(__('Save')) ?>
<?= $this->Form->end() ?>

Controller 文件

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
]}

实际的图像文件在哪里?我如何将它传递给 $new_image$user?非常感谢任何帮助或评论!提前致谢!

最佳答案

首先,不要在数据库中上传个人资料图像等二进制数据。第二点;只需将图像的文件名和位置存储在数据库中。让您的网站 HTML 从特定路径加载图像对您来说更加容易。然后你可以做:<img src="{$user->profile_image}" />或其他。

关于php - 使用 CakePHP3 将文件/图像上传到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45251570/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com