2013-09-10 53 views
1

我正在嘗試在文件上傳中使用Cake 2.3.8進行驗證,以確保只能上傳PDF。我懶散地基於這個this教程。用於文件上傳的CakePHP驗證

我的表單在輸入旁邊顯示星號,當我從模型中刪除驗證時,星號消失。我假設這意味着它「看到」驗證的輸入,但我無法弄清楚爲什麼即使自定義驗證沒有被觸發。

這裏的形式

echo $this->Form->create('Upload', array('type' => 'file')); 
echo $this->Form->input('file_upload', array('type' => 'file')); 
echo $this->Form->input('file_title'); 
echo $this->Form->end(__('Upload File!', true)); 

下面是我上傳模型

public function checkUpload(){ 
    echo "test"; //check to see if it reaches this...not displaying 
    return false; //the error message should be set just for testing, it's not displaying though 
} 


public $validate = array(
    'file_upload' => array(
     'extension' => array(
      'rule' => array('extension', array('pdf')), 
      'message' => 'Only pdf files', 
     ), 
     'upload-file' => array(
       'rule' => array('checkUpload'), 
       'message' => 'Error uploading file' 
     ) 
    ) 
); 

回答

0

的代碼,如果你嘗試在蛋糕調試某物,一直使用debug(sth) // sth could be variable could be string could be anything, cuz in Cake debug means

echo "<pre>"; 
print_r(sth); 
echo "</pre>";` 

它已經格式化很好。
然後之後你必須把die()否則後回聲......它會加載視圖,這就是爲什麼你不能看到它,即使有輸出。

+0

什麼是某事?我試着完全是這樣的,它說:「使用未定義的常量......假設'......' – user2443591

+0

lol ... sth表示你想調試的東西....在這種情況下,你可以做調試(」這裏「); – Geoffreyirl

+0

你得到這個錯誤意味着你已經輸入了函數checkUpload – Geoffreyirl

2

這裏是我的回答(雖然爲cakephp 1.3):

在你model添加以下validation$validate變量。

$this->validate = array(... 

    // PDF File 
    'pdf_file' => array(
     'extension' => array(
      'rule' => array('extension', array('pdf')), 
      'message' => 'Only pdf files', 
     ), 
     'upload-file' => array(
      'rule' => array('uploadFile'), // Is a function below 
      'message' => 'Error uploading file' 
     ) 
    ) 

); // End $validate 


/** 
* Used when validating a file upload in CakePHP 
* 
* @param Array $check Passed from $validate to this function containing our filename 
* @return boolean True or False is passed or failed validation 
*/ 
public function uploadFile($check) 
{ 
    // Shift the array to easily acces $_POST 
    $uploadData = array_shift($check); 

    // Basic checks 
    if ($uploadData['size'] == 0 || $uploadData['error'] !== 0) 
    { 
     return false; 
    } 

    // Upload folder and path 
    $uploadFolder = 'files'. DS .'charitylogos'; 
    $fileName = time() . '.pdf'; 
    $uploadPath = $uploadFolder . DS . $fileName; 

    // Make the dir if does not exist 
    if(!file_exists($uploadFolder)){ mkdir($uploadFolder); } 

    // Finally move from tmp to final location 
    if (move_uploaded_file($uploadData['tmp_name'], $uploadPath)) 
    { 
     $this->set('logo', $fileName); 
     return true; 
    } 

    // Return false by default, should return true on success 
    return false; 
} 

您可能必須自己顯示錯誤驗證消息,你可以使用這樣做:

<!-- The classes are for twitter bootstrap 3 - replace with your own --> 
<?= $form->error('pdf_file', null, array('class' => 'text-danger help-block'));?>