github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume4/section2/gopherface/endpoints/saveuserprofileimage.go (about) 1 package endpoints 2 3 import ( 4 "io/ioutil" 5 "log" 6 "mime" 7 "net/http" 8 "os" 9 "strings" 10 11 "github.com/EngineerKamesh/gofullstack/volume4/section2/gopherface/common/authenticate" 12 "github.com/EngineerKamesh/gofullstack/volume4/section2/gopherface/common/utility" 13 "github.com/EngineerKamesh/gofullstack/volume4/section2/gopherface/tasks" 14 15 "github.com/EngineerKamesh/gofullstack/volume4/section2/gopherface/common" 16 ) 17 18 func SaveUserProfileImageEndpoint(env *common.Env) http.HandlerFunc { 19 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 20 21 gfSession, err := authenticate.SessionStore.Get(r, "gopherface-session") 22 if err != nil { 23 log.Print(err) 24 return 25 } 26 uuid := gfSession.Values["uuid"].(string) 27 28 reqBody, err := ioutil.ReadAll(r.Body) 29 30 if err != nil { 31 log.Print("Encountered error when attempting to read the request body: ", err) 32 } 33 34 contentType := http.DetectContentType(reqBody) 35 extensions, err := mime.ExtensionsByType(contentType) 36 37 if err != nil { 38 log.Print(err) 39 } 40 41 var extension string 42 43 if len(extensions) > 0 { 44 extension = extensions[0] 45 } 46 47 if extension != "" { 48 49 // Remove the existing profile image and its thumbnail (if they exist) 50 u, err := env.DB.GetUserProfile(uuid) 51 52 if err != nil { 53 log.Println(err) 54 } 55 56 if u.ProfileImagePath != "" { 57 os.Remove(WebAppRoot + u.ProfileImagePath) 58 os.Remove(strings.Replace(WebAppRoot+u.ProfileImagePath, "_thumb", "", -1)) 59 60 } 61 62 randomFileName := utility.GenerateUUID() 63 imageFilePathWithoutExtension := "/static/uploads/images/" + randomFileName 64 err = ioutil.WriteFile(WebAppRoot+imageFilePathWithoutExtension+extension, reqBody, 0666) 65 if err != nil { 66 log.Println(err) 67 } 68 69 thumbnailResizeTask := tasks.NewImageResizeTask(WebAppRoot+imageFilePathWithoutExtension, extension) 70 thumbnailResizeTask.Perform() 71 72 // Update the database record to the path of the image file 73 env.DB.UpdateUserProfileImage(uuid, imageFilePathWithoutExtension+"_thumb"+extension) 74 75 w.Write([]byte(imageFilePathWithoutExtension + "_thumb" + extension)) 76 77 } else { 78 w.Write([]byte("Error: Failed to process uploaded file.")) 79 80 } 81 82 }) 83 }