繁体   English   中英

在cakephp中上传文件

[英]file upload in cakephp

如何使用cakephp上传文件? 文件上传是否有任何框架支持,或者我应该为此编写自己的代码?

编辑(2015):请参阅Awesome CakePHP列表以获取当前文件插件( 此处为2.x分支)


原始答案:

CakePHP正在积极开发中上传插件(截至2010年10月):

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

两者都有可能

对于初学者来说,这可能是更好的选择: http : //www.milesj.me/resources/script/uploader-plugin

要开始尝试这个。

我花了两天时间寻找一种上传文件的简单方法,我尝试了很多方法,但没有任何效果。 这可行。 它是不安全的,它是超基本的。 对我来说,现在是一个跳板。 我将用它来了解流程。 然后,您可以提高其复杂性。

对我来说,我在尝试保存$this->data很费劲-但是,它的原因不像cakePHP博客教程。 您想要的数据(所有文件信息)被嵌套在嵌套数组中$this->data['Doc']['files']因此$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 {
    }
?>

视图

<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();
?>

控制器

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM