MCPcopy Index your code
hub / github.com/TruthHun/DocHub / Avatar

Method Avatar

controllers/HomeControllers/UserController.go:732–792  ·  view source on GitHub ↗

更换头像

()

Source from the content-addressed store, hash-verified

730
731//更换头像
732func (this *UserController) Avatar() {
733
734 if this.IsLogin == 0 {
735 this.ResponseJson(false, "请先登录")
736 }
737
738 dir := fmt.Sprintf("./uploads/%v/%v", time.Now().Format("2006-01-02"), this.IsLogin)
739 os.MkdirAll(dir, 0777)
740 f, fh, err := this.GetFile("Avatar")
741 if err != nil {
742 helper.Logger.Error("用户(%v)更新头像失败:%v", this.IsLogin, err.Error())
743 this.ResponseJson(false, "头像文件上传失败")
744 }
745 defer f.Close()
746
747 ext := strings.ToLower(strings.TrimLeft(filepath.Ext(fh.Filename), "."))
748 if !(ext == "jpg" || ext == "jpeg" || ext == "png" || ext == "gif") {
749 this.ResponseJson(false, "头像图片格式只支持jpg、jpeg、png和gif")
750 }
751
752 tmpFile := dir + "/" + helper.MD5Crypt(fmt.Sprintf("%v-%v-%v", fh.Filename, this.IsLogin, time.Now().Unix())) + "." + ext
753 saveFile := helper.MD5Crypt(tmpFile) + "." + ext
754 err = this.SaveToFile("Avatar", tmpFile)
755 if err != nil {
756 helper.Logger.Error("用户(%v)头像保存失败:%v", this.IsLogin, err.Error())
757 this.ResponseJson(false, "头像文件保存失败")
758 }
759
760 //头像裁剪
761 if err = helper.CropImage(tmpFile, helper.AvatarWidth, helper.AvatarHeight); err != nil {
762 helper.Logger.Error("图片裁剪失败:%v", err.Error())
763 }
764
765 var cs *models.CloudStore
766 if cs, err = models.NewCloudStore(false); err != nil {
767 helper.Logger.Error(err.Error())
768 this.ResponseJson(false, "内部服务错误:云存储连接失败")
769 }
770
771 err = cs.Upload(tmpFile, saveFile)
772 if err != nil {
773 helper.Logger.Error(err.Error())
774 this.ResponseJson(false, "头像文件保存失败")
775 }
776 os.RemoveAll(tmpFile)
777
778 //查询数据库用户数据
779 var user = models.User{Id: this.IsLogin}
780 orm.NewOrm().Read(&user)
781 oldAvatar := user.Avatar
782 user.Avatar = saveFile
783 rows, err := orm.NewOrm().Update(&user, "Avatar")
784 if rows > 0 && err == nil {
785 this.ResponseJson(true, "头像更新成功")
786 go cs.Delete(oldAvatar)
787 }
788 if err != nil {
789 helper.Logger.Error(err.Error())

Callers

nothing calls this directly

Calls 4

UploadMethod · 0.95
DeleteMethod · 0.95
UpdateMethod · 0.80
ResponseJsonMethod · 0.45

Tested by

no test coverage detected