CakePHP4已上传至webroot/img的图片无法在视图中显示问题求助
问题解决方案
核心问题排查
- 时间戳不一致:你在判断目录、创建目录、路径拼接时多次调用
date("Ymdhms"),两次调用哪怕间隔1秒,生成的时间戳就会不同,导致数据库存储的路径和实际文件存放路径不匹配。 - 文件命名逻辑错误:实际存入目录的文件名为原始文件名,但是写入数据库的路径多了一层时间戳前缀,路径完全对应不上。
- 目录权限不足:创建目录时使用0744权限,大部分web服务器运行用户没有目录读取权限,会导致静态资源无法被访问。
修复后的代码
替换控制器的add方法代码即可:
public function add() { $post = $this->Posts->newEmptyEntity(); if ($this->request->is('post')) { $post = $this->Posts->patchEntity($post, $this->request->getData()); $file = $this->request->getData("titleImg_file_name"); // 提前生成唯一时间戳,避免多次调用date导致不一致 $timeStamp = date("Ymdhms"); $imgBasePath = WWW_ROOT . "img" . DS . $timeStamp; // 判断目录是否存在,不存在则递归创建 if (!file_exists($imgBasePath)) { mkdir($imgBasePath, 0755, true); } $targetFilePath = $imgBasePath . DS . $file["name"]; // 移动文件成功后再赋值路径到实体 if (move_uploaded_file($file["tmp_name"], $targetFilePath)) { $post->titleImg_file_name = $timeStamp . "/" . $file["name"]; } if ($this->Posts->save($post)) { $this->Flash->success(__('The post has been saved.')); return $this->redirect(['action' => 'index']); } $this->Flash->error(__('The post could not be saved. Please, try again.')); } $users = $this->Posts->Users->find('list', ['limit' => 200]); $tags = $this->Posts->Tags->find('list', ['limit' => 200]); $this->set(compact('post', 'users',"tags")); }
操作步骤
- 删除之前已经上传的错误目录和数据库内的无效测试数据
- 替换上述修复后的add方法代码
- 重新上传图片测试即可,原有视图层代码无需修改,CakePHP的
Html->image()方法会自动拼接/img/前缀,可正常渲染图片。
内容的提问来源于stack exchange,提问作者Takato Komori
相关产品推荐
相关产品推荐

