at_yasu's blog

ロード的なことを

File Upload

File Upload handlerにこれを使ってるのですが、ディレクトリーを作るわファイル名は日本語非対応だからぐでぐでだわで、その部分を修正したのと、丸一日ハマってたので利用方法メモ。

SQL/Model

DB自体はそのままマニュアルやリンク先に書いている方法そのまま。

Controller

コントーラー部。使用するModelなどをvar $user=array(...);で指定しないと泣きの涙を見ます。controller.phpを頭から読みましたよ。。。

実際の処理部分。本当はエラー処理とかした方が良いんだけど、ファイルをあえて変更しないとかがあり得るので、簡単にすまして放置。

function edit ($id = null)
{
	$this->Oblbook->id = $id;
	if (empty($this->data)) {
		$this->data = $this->Oblbook->read();
	}
	else {
		if ($this->Oblbook->save($this->data['Oblbook'])) {
			($this->FileHandler->upload('file', OBLBOOKS_THUMB_UPDIR));
			if ($this->FileHandler->isError)
					echo $this->FileHandler->errorMessage;
			$this->flash('updated.', '/oblbooks/', 5);
		}
	}
}

View

結構厄介でしたが、あっさり動きました。サンプルコード自体が1.1のようでハマりましたが・・・

<?php
echo $form->create('Oblbook', array('action' => 'add', 'type' => 'file'));
echo $form->input('name');
echo $form->input('creatername');
echo $form->input('price');
?>
<label for='thumbs'>Thumbnail</label>: 
<input type="file" id='thumbs' name="file[]"/>
<?php
	echo $form->end('Save Post');
?>

Handler

処理の中枢部分。アップロードされたファイルの処理やDBへのinsertをしている。

差分を此処に投下しておきます。

158c158
< 			$dir .= uniqid($this->_prefix) . DS;
---
> 			//$dir .= uniqid($this->_prefix) . DS;
161c161
< 			if (!mkdir($dir)) {
---
> 			//if (!mkdir($dir)) {
163,166c163,166
< 				$this->_setError('The folder ('.$dir.') for the file upload could not be created.');
< 				if ($this->_debugLevel == 0) {
< 					$this->_setError('There was an error uploading.  Please try again.');
< 				}
---
> 			//	$this->_setError('The folder ('.$dir.') for the file upload could not be created.');
> 			//	if ($this->_debugLevel == 0) {
> 			//		$this->_setError('There was an error uploading.  Please try again.');
> 			//	}
168c168
< 				return false;
---
> 			//	return false;
170c170
< 			} else {
---
> 			//} else {
180c180
< 			}
---
> 			//}
398a399,401
> 			
> 			
> 			//$this->controller->constructClasses();
403c406
< 			// Update database, set error on failure										  
---
> 			// Update database, set error on failure  
456a460,464
> 	
> 			// File name is uniq
> 			$exdata = pathinfo(basename($value));
> 			$filename = md5(uniqid(mt_rand(), true)) . '.' . $exdata['extension'];
> 			
458c466
< 				'name' => $value,
---
> 				'name' => $filename,