From b65d1350e340bd9311a44b8f8db2e059ee296e0e Mon Sep 17 00:00:00 2001 From: link Date: Tue, 2 Jan 2024 06:20:48 +0000 Subject: [PATCH] add get avatar function --- route/v1.go | 1 + route/v1/user.go | 32 +++++++++++++++++++++++++++++++- 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/route/v1.go b/route/v1.go index 9413d57..0c97230 100644 --- a/route/v1.go +++ b/route/v1.go @@ -60,6 +60,7 @@ func InitRouter() *gin.Engine { v1UsersGroup.DELETE("/current/image", v1.DeleteUserImage) v1UsersGroup.PUT("/avatar", v1.PutUserAvatar) + v1UsersGroup.GET("/avatar", v1.PutUserAvatar) v1UsersGroup.DELETE("/:id", v1.DeleteUser) v1UsersGroup.GET("/:username", v1.GetUserInfoByUsername) diff --git a/route/v1/user.go b/route/v1/user.go index 60182f1..71259db 100644 --- a/route/v1/user.go +++ b/route/v1/user.go @@ -172,7 +172,8 @@ func PutUserAvatar(c *gin.Context) { imgBase64 := strings.Replace(data, "data:image/png;base64,", "", 1) decodeData, err := base64.StdEncoding.DecodeString(string(imgBase64)) if err != nil { - panic(err) + c.JSON(http.StatusInternalServerError, model.Result{Success: common_err.SERVICE_ERROR, Message: err.Error()}) + return } // 将字节数组转为图片 @@ -204,6 +205,35 @@ func PutUserAvatar(c *gin.Context) { }) } +// @Summary get user head +// @Produce application/json +// @Tags user +// @Param file formData file true "用户头像" +// @Security ApiKeyAuth +// @Success 200 {string} string "ok" +// @Router /users/avatar [get] +func GetUserAvatar(c *gin.Context) { + id := c.GetHeader("user_id") + user := service.MyService.User().GetUserInfoById(id) + if user.Id == 0 { + c.JSON(common_err.SERVICE_ERROR, + model.Result{Success: common_err.USER_NOT_EXIST, Message: common_err.GetMsg(common_err.USER_NOT_EXIST)}) + return + } + + if file.Exists(user.Avatar) { + // @tiger - RESTful 规范下不应该返回文件本身内容,而是返回文件的静态URL,由前端去解析 + c.Header("Content-Disposition", "attachment; filename*=utf-8''"+url2.PathEscape(path.Base(user.Avatar))) + c.File(user.Avatar) + return + } + c.JSON(http.StatusNotFound, + model.Result{ + Success: common_err.SERVICE_ERROR, + Message: user.Avatar + " not found", + }) +} + // @Summary edit user name // @Produce application/json // @Accept application/json