1.js
$("input#upload").change(function () { $.ajaxFileUpload({ url: '/members/web-members-rest/upload.html', secureuri: false, data:{'id':id}, fileElementId:'upload', dataType: 'xml', success: function (data, status) { if ($(data).find("result").text() == 'Success') { //上传成功 } else{ alert("上传失败"); } }, error: function (data, status, e) { return; } }); }); $("a.upload").click(function(){$("input#upload").click();});
2.htm
<a href='javascript:;' class="upload">上传</a> <div style="display:none"><input type="file" id="upload" name="UploadForm[file]" /></div> 这个name很重要 <img data-name="img" src="blank.gif" />
3.php,rest
public function actionUpload(){ $params=Yii::$app->request->post(); $model = new UploadForm(); if (Yii::$app->request->isPost) { $model->file = UploadedFile::getInstance($model, 'file'); if ($model->file && $model->validate()) { if(!file_exists('data/upload/'.$uid))mkdir('data/upload/'.$uid); $path='data/upload/'; if(!file_exists($path))mkdir($path); $filename=$params['id'].'.' . $model->file->extension; if($model->file->saveAs($path.$filename)) return ["result"=>"Success","url"=>$path.$filename]; else return ["result"=>"Fail"]; } return ["result"=>"ValidFail"]; } return ["result"=>"PostFail"];