Created
March 23, 2019 05:23
-
-
Save sanderhelleso/82323b8a1b0681b0c4bfe56ac0d526eb to your computer and use it in GitHub Desktop.
Avatar(file) upload from form data in go
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Takes a valid file(png/jpg) from form data, | |
creates a unique user directory to store file | |
and lastly re-size the file to passed in dimmensions | |
and copies the filebytes to the directory | |
*/ | |
// AvatarUpload handle uploading of a users profile avatar | |
func (p *Profiles) AvatarUpload(c *gin.Context) { | |
// get uploaded file | |
fHeader, _ := c.FormFile("avatar") | |
ext := strings.ToLower((filepath.Ext(fHeader.Filename))) | |
// check ext | |
if !(ext == ".jpg" || ext == ".png") { | |
response.RespondWithError( | |
c, | |
http.StatusInternalServerError, | |
"Only files of type JPG or PNG are allowed.", | |
) | |
return | |
} | |
file, err := fHeader.Open() | |
if err != nil { | |
uploadAvatarErr(c) | |
return | |
} | |
defer file.Close() | |
// create dir path for avatar | |
avatarPath := fmt.Sprintf("images/avatars/%v/", parser.GetIDFromCTX(c)) | |
err = os.MkdirAll(avatarPath, 0755) | |
if err != nil { | |
uploadAvatarErr(c) | |
return | |
} | |
// create destination file | |
dst, err := os.Create(avatarPath + "avatar.jpg") | |
if err != nil { | |
uploadAvatarErr(c) | |
return | |
} | |
defer dst.Close() | |
// rezise and store avatar in users path | |
err = jpeg.Encode(dst, resizeImg(150, 150, file), nil) | |
if err != nil { | |
uploadAvatarErr(c) | |
return | |
} | |
// notify user that upload wa successfull | |
response.RespondWithSuccess( | |
c, | |
http.StatusCreated, | |
"Avatar successfully uploaded!") | |
} | |
// resize image file to passed inn demensions | |
// using Lanczos resampling and preserve aspect ratio | |
func resizeImg(width uint, height uint, file multipart.File) image.Image { | |
img, _, err := image.Decode(file) | |
defer file.Close() | |
if err != nil { | |
fmt.Println(err) | |
panic(err) | |
} | |
new := resize.Resize(height, width, img, resize.Lanczos3) | |
return new | |
} | |
// helper func to send error message releated to avatar upload | |
func uploadAvatarErr(c *gin.Context) { | |
response.RespondWithError( | |
c, | |
http.StatusInternalServerError, | |
"Something went wrong when uploading image. Please try again.", | |
) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment