Cakephp:如何从文件夹中检索我的媒体文件以显示在我的视图页面上

时间:2013-07-17 16:03:50

标签: cakephp file-upload cakephp-2.0 cakephp-2.1

我正在开发一个Cakephp 2.x ..我现在所做的就是..我正在向用户显示一个表格,其中我已经给了他选择上传音频文件..所以我采取了来自用户的文件..我正在将文件保存到app / uploads文件夹..以及进入数据库的路径...现在问题是我怎么知道检索我的音频文件并将它们显示到我的视图页面< / p>

这是我的上传功能

 public function audio(){


    if ($this->request->isPost()){
        $this->loadModel('Audio');
        $file = $this->request->data['Audio']['file'];

         $idUser = $this->Auth->user('idUser');


        if ($file['error'] === UPLOAD_ERR_OK) {
            $id = String::uuid();
            $name =$file['name'];

            $folder_url = APP.'uploads/'.$idUser;
        if(!is_dir($folder_url)) {
            mkdir($folder_url);
        }
        move_uploaded_file($file['tmp_name'],  $folder_url.DS.$name);

            $this->request->data['Audio']['User_id'] = $idUser;
            $this->request->data['Audio']['filename'] = $file['name'];
            $this->request->data['Audio']['filesize'] = $file['size'];
            $this->request->data['Audio']['filemime'] = $file['type'];
            $this->Audio->save($this->request->data);


            return true;
        }
    }
    return false;
  }

 public function showAllAudioFiles(){
   }

现在特定用户的文件已存入此文件夹 app / uploads / 23 / file.mp3

1 个答案:

答案 0 :(得分:0)

答案:

假设每个用户只有一个文件,那么你需要找到数据库记录并从中构建路径:

public function showAllAudioFiles(){
    $record = $this->Audio->find('first', array('conditions' => array('User_id' => $this->Auth->user('idUser')));
    $file = APP . 'uploads' . DS . $this->Auth->user('idUser') . DS . $record['Audio']['filename'] . '.' . $record['Audio']['filemime'];
    $this->set('file', $file);
}

如果用户可以拥有多个文件:

public function showAllAudioFiles(){
    $records = $this->Audio->find('all', array('conditions' => array('User_id' => $this->Auth->user('idUser')));
    $files = array();
    foreach ($records as $record) {
        $files[] = APP . 'uploads' . DS . $this->Auth->user('idUser') . DS . $record['Audio']['filename'] . '.' . $record['Audio']['filemime'];
    }
    $this->set('files', $files);
}

现在,$file变量将包含格式为 app / uploads / 23 / file.mp3 的字符串。或者$files将是这些字符串的数组。

建议:

使用正确的'Cake'方式,您只需检索记录并使用media的{​​{1}}方法回显它们:

ACTION:

HtmlHelper

查看:

public function showAllAudioFiles(){
        $record = $this->Audio->find('first', array('conditions' => array('User_id' => $this->Auth->user('idUser')));
        $this->set('file', $record);
}

这应输出如下内容:

echo $this->Html->media($file['Audio']['filename'] . '.' . $file['Audio']['filemime'],
    array('pathPrefix' => 'uploads' . DS . $file['Audio']['User_id']
);

创建指向文件的链接

编辑:对于文件的链接,只需使用HtmlHelper的 <audio src="/uploads/23/file.mp3"></audio> 方法:

link

HtmlHelper::media