Yii2 使用十二 配合ajaxFileUpload 上传文件

1.js

[javascript] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. $("input#upload").change(function () {  
  2.       $.ajaxFileUpload({  
  3.           url: '/members/web-members-rest/upload.html',  
  4.           secureuri: false,  
  5.           data:{'id':id},  
  6.           fileElementId:'upload',  
  7.           dataType: 'xml',  
  8.           success: function (data, status) {  
  9.               if ($(data).find("result").text() == 'Success') {  
  10.                   //上传成功  
  11.               }  
  12.               else{  
  13.                   alert("上传失败");  
  14.               }  
  15.           },  
  16.           error: function (data, status, e) {  
  17.               return;  
  18.           }  
  19.       });  
  20.   });  
  21.   $("a.upload").click(function(){$("input#upload").click();});  

2.htm

[html] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. <href='javascript:;' class="upload">上传</a>  
  2. <div style="display:none"><input type="file" id="upload" name="UploadForm[file]" /></div>  这个name很重要  
  3. <img data-name="img" src="blank.gif" />  
  4.       


3.php,rest

[php] view plain copy
 
 在CODE上查看代码片派生到我的代码片
    1.        public function actionUpload(){  
    2. $params=Yii::$app->request->post();  
    3.   
    4. $model = new UploadForm();  
    5. if (Yii::$app->request->isPost) {  
    6.     $model->file = UploadedFile::getInstance($model, 'file');  
    7.     if ($model->file && $model->validate()) {  
    8.         if(!file_exists('data/upload/'.$uid))mkdir('data/upload/'.$uid);  
    9.         $path='data/upload/';  
    10.         if(!file_exists($path))mkdir($path);  
    11.                   
    12.         $filename=$params['id'].'.' . $model->file->extension;  
    13.         if($model->file->saveAs($path.$filename))  
    14.             return ["result"=>"Success","url"=>$path.$filename];  
    15.                   
    16.         else return ["result"=>"Fail"];  
    17.     }  
    18.     return ["result"=>"ValidFail"];  
    19. }  
    20. return ["result"=>"PostFail"];  
原文地址:https://www.cnblogs.com/grimm/p/5444624.html