文件上傳是CakePHP不能開箱即用的,這是令我煩惱的關於框架的唯一的事情之一
我解決了這個問題使用回調方法將文件處理添加到模型中。我用beforeSave()
上傳實際文件,然後用beforeDelete()
從文件系統中刪除文件。樣本模型是這樣的:
<?php
App::uses('File', 'Utility');
class Image extends AppModel {
public $name = 'Image';
public function beforeSave($options = array()) {
$fieldName = 'filename';
$field = $this->data[$this->alias][$fieldName];
if (!is_array($field)) {
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
}
switch ($field['error']) {
case UPLOAD_ERR_OK:
$newFilename = time() . '.jpg';
$uploadDir = WWW_ROOT . 'files/';
$source = $field['tmp_name'];
$destination = $uploadDir . $newFilename;
if (move_uploaded_file($source, $destination)) {
$this->data[$this->alias][$fieldName] = $newFilename;
return true;
}
else {
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
}
break;
default:
$this->validationErrors[$fieldName][] = 'No file detected';
return false;
break;
}
}
public function beforeDelete($cascade = true) {
$image = $this->findById($this->id);
$file = new File(WWW_ROOT . 'files/' . $image['Image']['filename']);
return $file->delete();
}
}
顯然,這不是一個完美的執行,可以隨意從中取,從失敗中學習,適應它。
對於最近只有一個模型附有圖像的項目,這是最新編寫的,但是對於一個更大的項目,我很可能會將其包含在一個很好的模型行爲中。
爲什麼'APP。 「views''?這不應該包含上傳的數據。使用'APP。 '文件'或'APP。 「webroot''。 – mark