1

我正在尝试在文件上传时使用 cake 2.3.8 进行验证,以确保只能上传 PDF。我松散地基于教程。

我的表单在输入旁边显示星号,当我从模型中删除验证时,星号消失。我假设这意味着它“看到”了验证输入,但我就是不明白为什么甚至没有触发自定义验证。

这是表格

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'
          )
    )
);
4

2 回答 2

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'));?>
于 2014-01-23T13:04:49.303 回答
0

如果您尝试在 Cake 中调试某事,请始终使用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()在 echo sth 之后放置其他内容,它会加载视图,这就是为什么即使有输出也看不到它的原因。

于 2013-09-11T00:00:39.087 回答