利用你的Product.php模型文件.......
public $validate = array(
'photo_name' => array(
'uploadError' => array(
'rule' => 'uploadError',
'message' => 'Something went wrong with the file upload',
'required' => FALSE,
'allowEmpty' => TRUE,
),
'photoSize' => array(
'rule' => array('fileSize','<=','2MB'),
'message' => 'Photo size must be less then 2MB.',
'required' => FALSE,
'allowEmpty' => TRUE,
),
'mimeType' => array(
'rule' => array('mimeType', array('image/gif','image/png','image/jpg','image/jpeg')),
'message' => 'Invalid file, only images allowed',
'required' => FALSE,
'allowEmpty' => TRUE
),
'processUpload' => array(
'rule' => 'processUpload',
'message' => 'Something went wrong processing your file',
'required' => FALSE,
'allowEmpty' => TRUE,
'last' => TRUE,
)
)
);
public $uploadDir = 'img/user_photos';
/**
* Process the Upload
* @param array $check
* @return boolean
*/
public function processUpload($check=array()) {
// deal with uploaded file
if (!empty($check['photo_name']['tmp_name'])) {
// check file is uploaded
if (!is_uploaded_file($check['photo_name']['tmp_name'])) {
return FALSE;
}
// build full filename
$filename = WWW_ROOT . $this->uploadDir . DS . String::uuid().'.'.pathinfo($check['photo_name']['name'], PATHINFO_EXTENSION);
// @todo check for duplicate filename
// try moving file
if (!move_uploaded_file($check['photo_name']['tmp_name'], $filename)) {
return FALSE;
// file successfully uploaded
} else {
// save the file path relative from WWW_ROOT e.g. uploads/example_filename.jpg
$this->data[$this->alias]['filepath'] = str_replace(DS, "/", str_replace(WWW_ROOT.IMAGES_URL, "", $filename));
}
}
return TRUE;
}
/**
* Before Save Callback
* @param array $options
* @return boolean
*/
public function beforeSave($options = array()) {
// a file has been uploaded so grab the filepath
if (!empty($this->data[$this->alias]['filepath'])) {
$this->data[$this->alias]['photo_name'] = $this->data[$this->alias]['filepath'];
}
return parent::beforeSave($options);
}
public function beforeValidate($options = array()) {
// ignore empty file - causes issues with form validation when file is empty and optional
if (!empty($this->data[$this->alias]['photo_name']['error']) && $this->data[$this->alias]['photo_name']['error']==4 && $this->data[$this->alias]['photo_name']['size']==0) {
unset($this->data[$this->alias]['photo_name']);
}
parent::beforeValidate($options);
}
以及它不是我的代碼,我忘記了它的來源。
不適合我...不上傳,文件路徑未被髮送到數據庫 –
您正在使用哪個CakePHP版本?有沒有錯誤信息?嘗試更改爲$ uploadDir ='img'; –
我正在使用2.4.6穩定,沒有任何錯誤。這種改變並沒有改變,我認爲這只是文件存儲的目錄。由於路徑沒有被保存,所以我認爲其他的東西是錯誤的 –