Skip to content

Commit

Permalink
完成从 Gravatar 获取头像
Browse files Browse the repository at this point in the history
  • Loading branch information
jimmykuu committed Feb 13, 2019
1 parent 4f1f5e9 commit 5a7d96b
Show file tree
Hide file tree
Showing 4 changed files with 109 additions and 26 deletions.
42 changes: 19 additions & 23 deletions apis/upload.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"errors"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"strings"
Expand All @@ -21,7 +20,18 @@ type UploadImage struct {

// Post /upload/image
func (a *UploadImage) Post() interface{} {
filename, err := saveImage(a.Req(), []string{"upload", "image"}, -1)
file, header, err := a.Req().FormFile("image")
if err != nil {
return map[string]interface{}{
"status": 0,
"message": fmt.Sprintf("图片上传失败(%s)", err.Error()),
}
}
defer file.Close()

fileType := header.Header["Content-Type"][0]

filename, err := saveImage(file, fileType, []string{"upload", "image"}, -1)
if err != nil {
return map[string]interface{}{
"status": 0,
Expand All @@ -42,31 +52,22 @@ type Sizer interface {
// uploadImage 上传图片,保存图片到指定位置,并返回图片 URL 地址
// maxSize: byte 如果是 -1,不检查图片大小
// 返回:文件名
func saveImage(r *http.Request, folders []string, maxSize int64) (string, error) {
file, header, err := r.FormFile("image")
if err != nil {
return "", err
}

fileSize := file.(Sizer).Size()

func saveImage(source io.Reader, fileType string, folders []string, maxSize int64) (string, error) {
if maxSize > 0 {
fileSize := source.(Sizer).Size()

if fileSize > maxSize {
return "", errors.New(fmt.Sprintf("图片尺寸大于 %dK,请选择 %dK 以内的图片上传", maxSize/1024, maxSize/1024))
}
}

defer file.Close()

// 检查是否是 jpg/png/gif 格式
uploadFileType := header.Header["Content-Type"][0]

filenameExtension := ""
if uploadFileType == "image/jpeg" {
if fileType == "image/jpeg" {
filenameExtension = ".jpg"
} else if uploadFileType == "image/png" {
} else if fileType == "image/png" {
filenameExtension = ".png"
} else if uploadFileType == "image/gif" {
} else if fileType == "image/gif" {
filenameExtension = ".gif"
}

Expand All @@ -82,12 +83,7 @@ func saveImage(r *http.Request, folders []string, maxSize int64) (string, error)
return "", err
}

io.Copy(toFile, file)
io.Copy(toFile, source)

return filename, nil

// return "", map[string]interface{}{
// "status": 1,
// "image_url": fmt.Sprintf("https://is.golangtc.com/upload/%s/%s", strings.Join(folders, "/"), filename),
// }
}
59 changes: 58 additions & 1 deletion apis/user_center.go
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
package apis

import (
"crypto/md5"
"fmt"
"io"
"net/http"
"strings"

"github.com/pborman/uuid"
Expand Down Expand Up @@ -167,7 +170,18 @@ type UploadAvatarImage struct {

// Post /api/user_center/upload_avatar
func (a *UploadAvatarImage) Post() interface{} {
filename, err := saveImage(a.Req(), []string{"avatar"}, 500*1024)
file, header, err := a.Req().FormFile("image")
if err != nil {
return map[string]interface{}{
"status": 0,
"message": fmt.Sprintf("图片上传失败(%s)", err.Error()),
}
}
defer file.Close()

fileType := header.Header["Content-Type"][0]

filename, err := saveImage(file, fileType, []string{"avatar"}, 500*1024)
if err != nil {
return map[string]interface{}{
"status": 0,
Expand Down Expand Up @@ -245,3 +259,46 @@ func (a *SetAvatar) Put() interface{} {
},
}
}

// FromGravatar 从 Gravatar 获取头像
type FromGravatar struct {
Base
binding.Binder
}

// Get /api/user_center/from_gravatar
func (a *FromGravatar) Get() interface{} {
h := md5.New()
io.WriteString(h, a.User.Email)
url := fmt.Sprintf("http://www.gravatar.com/avatar/%x?s=%d", h.Sum(nil), 256)

resp, err := http.Get(url)
if err != nil {
return map[string]interface{}{
"status": 0,
"message": fmt.Sprintf("获取头像失败(%s)", err.Error()),
}
}
defer resp.Body.Close()

fileType := resp.Header["Content-Type"][0]

filename, err := saveImage(resp.Body, fileType, []string{"avatar"}, -1)
if err != nil {
panic(err)
}

c := a.DB.C(models.USERS)
c.Update(bson.M{"_id": a.User.Id_}, bson.M{"$set": bson.M{"avatar": filename}})

a.User.Avatar = filename

return map[string]interface{}{
"status": 1,
"avatars": []string{
a.User.AvatarImgSrc(128),
a.User.AvatarImgSrc(64),
a.User.AvatarImgSrc(32),
},
}
}
1 change: 1 addition & 0 deletions routes.go
Original file line number Diff line number Diff line change
Expand Up @@ -61,5 +61,6 @@ func setRoutes(t *tango.Tango) {
g.Put("/user_center/change_password", new(apis.UserChangePassword))
g.Post("/user_center/upload_avatar", new(apis.UploadAvatarImage))
g.Put("/user_center/set_avatar", new(apis.SetAvatar))
g.Get("/user_center/from_gravatar", new(apis.FromGravatar))
})
}
33 changes: 31 additions & 2 deletions templates/user_center/avatar.html
Original file line number Diff line number Diff line change
Expand Up @@ -89,12 +89,25 @@
put('/api/user_center/set_avatar', {
avatar: this.state.avatar
}).then((data) => {
this.setState({avatars: data.avatars});
if (data.status) {
this.setState({avatars: data.avatars});
} else {
alert(data.message);
}
});
}

handleFromGravatar = (e) => {
get('/api/user_center/from_gravatar').then((data) => {
if (data.status) {
this.setState({avatars: data.avatars});
} else {
alert(data.message);
}
});
}

handleChooseAvatarChange = (e) => {
console.log(e.target.value);
this.setState({avatar: e.target.value});
}

Expand Down Expand Up @@ -193,6 +206,22 @@
</form>);
} else {
gravatarClass = 'is-active';

form = (<div>
<div className="field is-horizontal">
<div className="field-label">
</div>
<div className="field-body">
<div className="field">
<div className="control">
<button className="button is-primary" onClick={this.handleFromGravatar}>
从 Gravatar 获取
</button>
</div>
</div>
</div>
</div>
</div>);
}

return (<div>
Expand Down

0 comments on commit 5a7d96b

Please sign in to comment.