[英]file upload in cakephp
如何使用cakephp上傳文件? 文件上傳是否有任何框架支持,或者我應該為此編寫自己的代碼?
編輯(2015):請參閱Awesome CakePHP列表以獲取當前文件插件( 此處為2.x分支)
原始答案:
CakePHP正在積極開發中上傳插件(截至2010年10月):
- David Persson的媒體插件 [ 幻燈片 ]
- WebTechNick的CakePHP文件上傳處理插件 [ 博客文章 ]
- Miles Johnson的Uploader插件 [ 網站 ]
- MeioCódigo的MeioUpload 2.0行為插件 [ 網站 ]
兩者都有可能
對於初學者來說,這可能是更好的選擇: 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.