【问题标题】:how to display image from webroot folder using the image pathname in cakephp?如何使用 cakephp 中的图像路径名显示 webroot 文件夹中的图像?
【发布时间】:2013-11-04 15:58:40
【问题描述】:

嘿,我是 cakephp 的新手。我创建了一个包含两个字段名称和图像文件的示例表单。我能够将图像名称和 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.'));
 }
}
}


 }
?>

【问题讨论】:

    标签: php cakephp-2.3


    【解决方案1】:

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

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

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

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

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

    【讨论】:

    • 当你有这样的查询时,你就有了一个很好的 SQL 注入漏洞......
    • 这不是为了将它复制粘贴到他的脚本中。这是为了演示。如果你要使用它,我不会担心:D,为了安全使用 mysql_real_escape_string($_POST['username'])
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 2021-12-07
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多