Yii2.0 微信头像取回本地

后台微信登录需取回用户的头像存在本地,避免用户更换头像时imgUrl失效.

/**
 *   文件上传
 *  图片的地址进行返回
 */
public function actionUpload ()
{
    $model = new UploadForm();
    $uploadSuccessPath = "";

    if (Yii::$app->request->isPost) {
        $model->file = UploadedFile::getInstance($model, "file");

        //文件上传存放的目录
        $adress = Url::to("@web/",true);
        $dir = "uploads/headimgs";

        if (!is_dir($dir)){
            mkdir($dir);
        }

        if ($model->validate()) {
            //文件名
            $fileName = date("dMYHis").'.'. $model->file->extension;
            $dir = $dir."/". $fileName;
            $model->file->saveAs($dir);

            // 保存的路径
            $uploadSuccessPath = $adress.$dir;

            //写入数据库
            $id = Yii::$app->user->identity->id;

            // 事务开始
            $transaction = Yii::$app->db->beginTransaction();
            $message = '<script>alert("修改失败,原因: 1.请检查图片格式,仅支持 jpg和png两种格式. 2.其他原因如网络问题. 3.图片过大! 请重新上传!");window.history.back();</script>';

            try{
                // 修改默认头像地址
                $uadmin = new UserAdminModel;
                $a = $uadmin->findOne(['user_id'=>$id]);
                if (!$a) {
                    $message = '<script>alert("未找到该管理员!");window.history.back();</script>';
                    throw new \yii\db\Exception($message);
                }

                $a->headimgurl = $uploadSuccessPath;

                if ($a->save()) {
                    $admin = new AdminWechat;
                    $awechat = $admin->findOne(['user_id'=>$id]);
                    // 若有绑定微信头像 则也替换微信头像
                    if ($awechat) {
                        // 删除原来的头像

                        preg_match('/\/([^\/]+\.[a-z]+)[^\/]*$/',$awechat->headimgurl,$match);
                        unlink("uploads/headimgs" .$match[0]);

                        $awechat->headimgurl = $uploadSuccessPath;

                        if (!$awechat->save()) {
                            throw new \yii\db\Exception($message);
                        }
                    }
                    echo '<script>alert("修改成功!");window.history.back();</script>';
                }else{
                    throw new \yii\db\Exception($message);
                }
                $transaction->commit();
            }
            catch (\Exception $e) {
                $transaction->rollBack();
                echo $e->getMessage();
            }
        }
    }
    else{
        echo '<script>alert("非法上传方式!");window.history.back();</script>';
    }
}



导航