Yii2 富头像上传
前台html:
1 <div class="xz_img2 text-center"> 2 <div class="images_flow" id="img_wrap" <?php if(!$model->head_pic){echo "style='display:none'";}else{echo "style='display:block'";}; ?>> 3 <img src="<?= StringHelper::isNullOrEmpty($model->head_pic) 4 ? 5 Url::to('@web/uploads/headpic/default.jpg') 6 : 7 Url::to('@web/'.$model->head_pic.'1.jpg'. '?v=' . time())?>" alt="" class="img-circle"> 8 <p style="line-height:50px;"><a href="#" id = 'pic'>上传图片</a></p> 9 </div> 10 </div> 11 <div class="container" id="main"> 12 <div class="demo " <?php if($model->head_pic){echo "style='display:none'";}else{echo "style='display:block'";}; ?>> 13 <p id="swfContainer"> 14 本组件需要安装Flash Player后才可使用,请从<a 15 href="http://dl.pconline.com.cn/html_2/1/114/id=8122&pn=0.html" 16 target="_blank">这里</a>下载安装。 17 </p> 18 <button type="button" id="upload" style="display:none;margin-top:8px;"> 19 20 </button> 21 </div>
前台js :
1 swfobject.addDomLoadEvent(function () { 2 var swf = new fullAvatarEditor("<?=Url::to('@web/assets/flash_upload/')?>fullAvatarEditor.swf", "<?=Url::to('@web/assets/flash_upload/')?>xpressInstall.swf", "swfContainer", { 3 id: 'swf', 4 upload_url: '<?=Url::to('upload-pic')?>?userid=<?=$model->id?>&username=<?=$model->name?>&_csrf=<?=Yii::$app->request->getCsrfToken()?>', //上传接口 5 method: 'post', //传递到上传接口中的查询参数的提交方式。更改该值时,请注意更改上传接口中的查询参数的接收方式 6 src_upload: 0, //是否上传原图片的选项,有以下值:0-不上传;1-上传;2-显示复选框由用户选择 7 avatar_box_border_width: 0, 8 avatar_sizes: '100*100|50*50|30*30', 9 avatar_sizes_desc: '100*100像素|50*50像素|30*30像素', 10 tab_visible:true, 11 browse_button_y:-30, 12 tab_font_size: 20, 13 }, function (msg) { 14 switch (msg.code) { 15 case 1 : 16 // alert("页面成功加载了组件!"); 17 break; 18 case 2 : 19 // 20 document.getElementById("upload").style.display = "inline"; 21 break; 22 case 3 : 23 if (msg.type == 0) { 24 alert("摄像头已准备就绪且用户已允许使用。"); 25 } 26 else if (msg.type == 1) { 27 alert("摄像头已准备就绪但用户未允许使用!"); 28 } 29 else { 30 alert("摄像头被占用!"); 31 } 32 break; 33 case 5 : 34 if (msg.type == 0) { 35 if (msg.content.sourceUrl) { 36 37 alert("原图已成功保存至服务器,url为:\n" + msg.content.sourceUrl + "\n\n" + "头像已成功保存至服务器,url为:\n" + msg.content.avatarUrls.join("\n\n") + "\n\n传递的userid=" + msg.content.userid + "&username=" + msg.content.username); 38 } 39 else { 40 var user_id = msg.content.userid; 41 var user_name = msg.content.username; 42 var url = '/hr/user-info/deal-image'+'?v='+ new Date().getTime(); 43 $.ajax({ 44 url:url, 45 type:'post', 46 dataType:'json', 47 data:{user_id: user_id}, 48 success:function(data){ 49 if(data.success){ 50 $('.demo').hide(); 51 $("#img_wrap").show(); 52 $("#img_wrap img").attr('src','/'+data.url+'1.jpg'+'?v='+ new Date().getTime()); 53 54 55 //window.location.reload(); 56 } 57 } 58 }); 59 //alert("头像已成功保存至服务器,url为:\n" + msg.content.avatarUrls.join("\n\n") + "\n\n传递的userid=" + msg.content.userid + "&username=" + msg.content.username); 60 } 61 } 62 break; 63 } 64 } 65 ); 66 document.getElementById("upload").onclick = function () { 67 swf.call("upload"); 68 }; 69 });
后台php:
1 /** 2 * 上传图片 3 */ 4 public function actionUploadPic() 5 { 6 $result = array(); 7 $result['success'] = false; 8 $success_num = 0; 9 $msg = ''; 10 //上传目录 11 $dir = "uploads/headpic"; 12 //$path = 'uploads/headpic/'; 13 // 取服务器时间+8位随机码作为部分文件名,确保文件名无重复。 14 $filename = date("YmdHis") . '_' . floor(microtime() * 1000) . '_' . mt_rand(100,999); 15 // 处理原始图片开始------------------------------------------------------------------------> 16 //默认的 file 域名称是__source,可在插件配置参数中自定义。参数名:src_field_name 17 $source_pic = isset($_FILES["__source"]) ? $_FILES["__source"] : ''; 18 //如果在插件中定义可以上传原始图片的话,可在此处理,否则可以忽略。 19 if ($source_pic) { 20 if ($source_pic['error'] > 0) { 21 $msg .= $source_pic['error']; 22 } else { 23 //原始图片的文件名,如果是本地或网络图片为原始文件名、如果是摄像头拍照则为 *FromWebcam.jpg 24 $sourceFileName = $source_pic["name"]; 25 //原始文件的扩展名(不包含“.”) 26 $sourceExtendName = substr($sourceFileName, strripos($sourceFileName, ".")); 27 //保存路径 28 $savePath = "$dir/php_source_$filename." . $sourceExtendName; 29 //当前头像基于原图的初始化参数(只有上传原图时才会发送该数据,且发送的方式为POST),用于修改头像时保证界面的视图跟保存头像时一致,提升用户体验度。 30 //修改头像时设置默认加载的原图url为当前原图url+该参数即可,可直接附加到原图url中储存,不影响图片呈现。 31 $init_params = $_POST["__initParams"]; 32 $result['sourceUrl'] = $savePath . $init_params; 33 move_uploaded_file($source_pic["tmp_name"], $savePath); 34 $success_num++; 35 } 36 } 37 //<------------------------------------------------------------------------处理原始图片结束 38 // 处理头像图片开始------------------------------------------------------------------------> 39 //头像图片(file 域的名称:__avatar1,2,3...)。 40 $avatars = array("__avatar1", "__avatar2", "__avatar3"); 41 $avatars_length = count($avatars); 42 $userId = $_POST["userid"]; 43 44 for ($i = 0; $i < $avatars_length; $i++) { 45 $avatar = $_FILES[$avatars[$i]]; 46 $avatar_number = $i + 1; 47 if ($avatar['error'] > 0) { 48 $msg .= $avatar['error']; 49 } else { 50 $path = 'uploads/headpic/' . $userId; 51 if(!file_exists($path)){ 52 mkdir($path, 0777); 53 chmod($path, 0777); 54 } 55 $savePath = "$path/".'face'.$_POST["userid"].'_'. $avatar_number.".jpg"; 56 $result['avatarUrls'][$i] = $savePath; 57 move_uploaded_file($avatar["tmp_name"], $savePath); 58 $success_num++; 59 } 60 } 61 //<------------------------------------------------------------------------处理头像图片结束 62 //upload_url中传递的额外的参数,如果定义的method为get请换为$_GET 63 $result["userid"] = $_POST["userid"]; 64 $result["username"] = $_POST["username"]; 65 66 $result['msg'] = $msg; 67 if ($success_num > 0) { 68 $result['success'] = true; 69 } 70 //返回图片的保存结果(返回内容为json字符串) 71 print json_encode($result); 72 }
注意问题:
upload_url: '<?=Url::to('upload-pic')?>?userid=<?=$model->id?>&username=<?=$model->name?>&_csrf=<?=Yii::$app->request->getCsrfToken()?>', //上传接口
中的参数 加上_csrf = <?=Yii::$app->request->getCsrfToken()?>