てきとう

ワーワーゆうとります

複数ファイルアップロードを行うよー

  • 目的

ローカルにあるjpgファイルを一度にドーンてUPしたい。そんでサーバーのimagesディレクトリに保存する。

  • 準備

こちらのextensionを使います。http://www.yiiframework.com/extension/pupload/
protected/extensions以下に設置。

  • Controller
public function actionUpload() {
	if(!empty($_POST)) {
		$tmp = $_FILES['uploader']['tmp_name'];
		$filename = $_FILES['file']['name'];
		$output_name = '/images/'.$filename;
		if (isset($tmp) && is_uploaded_file($tmp)) {
			if ($in = fopen($tmp, "rb")) {
				$out = fopen($output_name, "w+");
				while ($buff = fread($in,$_FILES['file']['size'])) {
					fwrite($out, $buff);
				}
			}
		} else {
			die('{"jsonrpc" : "2.0", "error" : {"code": 101, "message": "Failed to open input stream."}, "id" : "id"}');
		}
		fclose($in);
		fclose($out);
		unlink($filename);
		die('{"jsonrpc" : "2.0", "result" : "'+$filename+'を保存しました", "id" : "id"}');
	}
	$this->render('upload');
}
  • View
$this->widget('application.extensions.Plupload.PluploadWidget', array(
	'config' => array(
		'runtimes' => 'flash',
		'url' => '/image/upload/',
	),
	'filters' => array(
		array('title' => Yii::t('app', 'Images files'), 'extensions' => 'jpg'),
	),
	'id' => 'uploader', 
	'callbacks' => array('FileUploaded' => "function(up,file,response){
		var json = eval(response);
		var res = eval('('+json.response+')'); 
		$('#result').append($('<p />').text(res.result));
	}"
));
<div id="result">
アップロードの結果です。
</div>
  • 結果

f:id:ym1173:20130514191643p:plain
こんなのが出るので、Add Filesでファイルを思う存分選択し、Start uploadをクリック。
1ファイルUPごとにcallbacksで結果を受け取りアップロードの結果をjQueryでどんどこ出力する流れです。ざっくり。