我想在我的CakePHP程序納入上傳功能。我之前爲一個原始的PHP項目創建了一個,並決定重用該代碼,因爲我知道它的工作原理。代碼如下:無法上傳文件中的CakePHP 2
$allowed_filetypes = array('.jpg','.gif','.bmp','.png');
$max_filesize = 1000000; // Maximum filesize in BYTES
$upload_path = './files/';
$filename = $_FILES['userfile']['name'];
$desiredname = $_POST['desiredname'];
$ext = substr($filename, strpos($filename,'.'), strlen($filename)-1);
$savedfile = $desiredname.$ext;
// Check if the filetype is allowed, if not DIE and inform the user.
if(!in_array($ext,$allowed_filetypes))
die('The file you attempted to upload is not allowed.');
// Now check the filesize, if it is too large then DIE and inform the user.
if(filesize($_FILES['userfile']['tmp_name']) > $max_filesize)
die('The file you attempted to upload is too large.');
// Check if we can upload to the specified path, if not DIE and inform the user.
if(!is_writable($upload_path))
die('You cannot upload to the specified directory, please CHMOD it to 777.');
// Upload the file to your specified path.
if(move_uploaded_file($_FILES['userfile']['tmp_name'],$upload_path . $savedfile))
echo 'Your file upload was successful, view the file <a href="' . $upload_path . $savedfile . '" title="Your File">here</a>'; // It worked.
else
echo 'There was an error during the file upload. Please try again.'; // It failed :(.
我把這段代碼放到我想上傳的頁面的控制器中。我已經使用了表單助手在CakePHP中產生的形式,主要內容如下:
<?php
echo $this->Form->create('Customer', array(
'class' => 'form-horizontal',
'action' => 'add',
'enctype' => 'multipart/form-data'
));
echo $this->Form->input('filename', array(
'type' => 'text',
'label' => 'Filename',
'class' => 'span5'
));
echo $this->Form->input('file', array(
'between' => '<br />',
'type' => 'file'
));
echo $this->Form->end('Save Changes', array(
'label' => false,
'type' => 'submit',
'class' => 'btn btn-primary'
));
echo $this->Form->end();
?>
我已經改變到田間地頭的任何引用在我的舊代碼,以反映該項目中使用形式的變化。然而,我得到以下錯誤,當我提交表單:
通知(8):未定義指數:CustomerFile [APP \控制器\ CustomersController.php,線148]
通知(8):未定義的索引:CustomerFilename [APP \控制器\ CustomersController.php,線149]
在控制器中的代碼,我已(再次)改變表單字段使用以下:
$filename = $this->request->data['CustomerFile']['name'];
$desiredname = $this->request->data['CustomerFilename'];
但仍然出現了錯誤。我猜測,表單字段沒有被引用正確的,但我想我已經正確引用他們使用$this->request
代碼,但顯然沒有奏效。有沒有人有任何想法?