2010-10-12 86 views

回答

5

编辑(2015年):请参阅Awesome CakePHP列表当前文件的插件(2.x的分支here


原来的答复:

CakePHP的上传在积极开发插件(如十月的2010):

您也可以使用File class,但我不会在这一个上重新发明轮子。

+1

相关:http://stackoverflow.com/questions/3148203/best-practice-to-upload-files-in-cakephp/3162144#3162144 – deizel 2010-10-12 12:22:51

+1

你错过了https://github.com/burzum/cakephp-file -storage – burzum 2015-08-04 08:12:16

+1

谢谢@burzum,我已经指出了现在维护的列表的两个答案:) – deizel 2015-08-04 19:29:20

0

此组件可以帮助您:http://cakeforge.org/snippet/detail.php?type=snippet&id=36。 允许使用FTP上传到数据库或目录。我有一些CakePHP的经验,但是我还没有尝试过这个组件。

+0

Cakeforge不再使用(在2008年底通过thechaw取代,然后在2009年年底的GitHub),只保留现场提供的旧代码存档。这个特定的组件是为CakePHP 1.2编写的,并且自1.3稳定以来并没有更新。 – deizel 2010-10-12 12:35:11

0

要开始尝试这个。

我花了两天的时间寻找上传文件的简单方法,我尝试了很多方法,无法使用任何工具。这工作。这是不安全的,它是超级基础。对我来说,现在是一个跳板。我会用这个来理解过程。然后你就可以在复杂的环境中构建它。

对我来说,我努力尝试保存$this->data - 但因为它不像cakePHP博客教程。你想要的数据(所有的文件信息)在嵌套数组中被埋入几层,所以$this->data['Doc']['files']就是你所追求的。

SQL

CREATE TABLE IF NOT EXISTS `docs` (
    `id` int(11) NOT NULL AUTO_INCREMENT, 
    `name` varchar(300) NOT NULL, 
    `type` varchar(300) NOT NULL, 
    `tmp_name` varchar(300) NOT NULL, 
    `error` tinyint(1) NOT NULL, 
    `size` varchar(100) NOT NULL, 
    PRIMARY KEY (`id`) 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=7 ; 

模型

<?php 
    class Doc extends AppModel { 
    } 
?> 

VIEW

<h1>Uploads</h1> 
<table> 
    <tr> 
     <th>ID</th><th>File Name</th><th>Size</th> 
    </tr> 
<?php foreach($files as $file): ?> 
    <tr> 
     <td><?php echo $file['Doc']['id'];?></td> 
     <td><?php echo $this->Html->link($file['Doc']['name'],array('controller' => 'files','action'=>'uploads',$file['Doc']['name']));?></td> 
     <td><?php echo number_format($file['Doc']['size']/1023,0).' KB';?></td> 
    </tr> 
<?php endforeach;?> 
</table> 

<h1>Add a File</h1> 
<?php 
echo $this->Form->create('Doc',array('type'=>'file')); 
echo $this->Form->file('File'); 
echo $this->Form->submit('Upload'); 
echo $this->Form->end(); 
?> 

CON TROLLER

<?php 
class DocsController extends AppController 
{ 
    public $helpers = array('Html','Form','Session'); 
    public function index() 
    { 
     // -- list the files -- // 
     $this->set('files',$this->Doc->find('all')); 
     // -- Check for error -> Upload file to folder -> Add line to database -- // 
     if($this->request->is('post')) 
     { 
      if($this->data['Doc']['File']['error']=='0') 
      { 
       if(file_exists('files/uploads/' . $this->data['Doc']['File']['name'])) 
       { 
        $this->Session->setFlash('A file called ' .$this->data['Doc']['File']['name']. ' already exists'); 
       } else { 
        move_uploaded_file($this->data['Doc']['File']['tmp_name'], 'files/uploads/' . $this->data['Doc']['File']['name']); 
       } 
       $this->Doc->save($this->data['Doc']['File']); 
       $this->redirect(array('action'=>'index')); 
      } 
     } 
    } 
} 
?>