CakePHP アプリケーションにアップロード機能を組み込もうとしています。生の PHP プロジェクト用に以前にビルドしたことがあり、そのコードが機能することがわかっているため、そのコードを再利用することにしました。コードは次のとおりです。
$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 の FormHelper を使用しました。
<?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\Controller\CustomersController.php、148 行目]
通知 (8): 未定義のインデックス: CustomerFilename [APP\Controller\CustomersController.php、149 行目]
コントローラーのコードで、フォーム フィールドを (再び) 次のように変更しました。
$filename = $this->request->data['CustomerFile']['name'];
$desiredname = $this->request->data['CustomerFilename'];
しかし、エラーはまだ発生します。フォームフィールドが適切に参照されていないと推測していますが、コードを使用して適切に参照したと思っていました$this->request
が、明らかに機能していません。誰にもアイデアはありますか?