如何使用 CakePHP 中的图像路径名显示来自 Webroot 文件夹的图像


how to display image from webroot folder using the image pathname in cakephp?

Hai 我是蛋糕的新手。我创建了一个具有两个字段名称和图像文件的示例表单。我能够将图像名称和uername保存在数据库表中,并将图像保存在webroot文件夹中。现在我想使用特定 id 检索图像。如何使用特定用户 ID 从 webroot 文件夹中检索图像?。请帮助我提高我在 cakephp 方面的知识。

添加.ctp

<?php 
echo $this->Form->create('User', array('controller' => 'users', 'action' =>  
'add','type' => 'file','enctype' => 'multipart/form-data'));
echo $this->Form->input('name');
echo $this->Form->input('image', array('type' => 'file')); 
echo $this->Form->end('Submit');
?>

用户控制器.php

<?php
class UsersController extends AppController {
 public $helpers = array('Html', 'Form');
public function beforeFilter() {
    parent::beforeFilter();
    $this->Auth->allow('add','retrieve');
}
public function retrieve() 
{
  $this->loadModel('User');
$ret = $this->User->find('all');
    $this->set('retrieve', $ret);
}
public function add()
{
       if ($this->request->is('post')) {
        $this->User->create();
    $this->loadModel('User');
 $id = $this->request->data['User']['id'];
    $pathname = $this->request->data['User']['image']['tmp_name'];       
    $filename = $this->request->data['User']['image']['name'];
    $this->request->data['User']['image'] = $filename;
     if($this->User->save($this->request->data))
 {
        move_uploaded_file($pathname,  $_SERVER['DOCUMENT_ROOT'] . '/cakephp_image  
 /app/webroot/files/' . $filename);
     $this->Session->setFlash(__('The Image has been saved'));
    return $this->redirect(array('controller' => 'users', 'action' =>  
'retrieve'));   
   } 
else 
{
$this->Session->setFlash(__('The Image could not be saved. Please, try again.'));
 }
}
}

 }
?>

你能在这里发布你的代码吗? 没有它,就像在一年中建造城堡一样。对您的问题的简短回答是,首先从数据库中检索图像ID,然后像这样使用它

 <img src="<?php echo Router::url('/', true).'/'.$image_name'; //image name from database  ?>"></img>

现在,$image_name是您必须与用户名一起存储在数据库中的内容,因此当您有类似查询时

  Select * FROM `foo` where username="'.$_POST['username'].'"

它还将返回图像名称,您可以使用该名称从根文件夹中获取图像