0

はい、cakephp は初めてです。名前と画像ファイルの 2 つのフィールドを持つサンプル フォームを 1 つ作成しました。画像名と uername をデータベース テーブルに保存し、画像を webroot フォルダーに保存することができました。 id.特定のユーザー ID を使用して webroot フォルダーから画像を取得するにはどうすればよいですか?

Add.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');
?>

UserController.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.'));
 }
}
}


 }
?>
4

1 に答える 1

0

ここにコードを投稿できますか? それがなければ、年に城を建てるようなものになります。あなたの質問に対する簡単な答えは、最初にデータベースから画像IDを取得してから、このように使用することです

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

$image_name は、ユーザー名とともにデータベースに保存する必要があるため、次のようなクエリがある場合

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

ルートフォルダーから画像を取得するために使用できる画像名も返されます

于 2013-11-01T05:52:15.037 に答える