github.com/EngineerKamesh/gofullstack@v0.0.0-20180609171605-d41341d7d4ee/volume4/section3/gopherface/handlers/uploadimage.go (about) 1 package handlers 2 3 import ( 4 "io" 5 "log" 6 "net/http" 7 "os" 8 "path/filepath" 9 "strings" 10 11 "github.com/EngineerKamesh/gofullstack/volume4/section3/gopherface/common/asyncq" 12 "github.com/EngineerKamesh/gofullstack/volume4/section3/gopherface/common/utility" 13 "github.com/EngineerKamesh/gofullstack/volume4/section3/gopherface/tasks" 14 ) 15 16 type UploadImageForm struct { 17 PageTitle string 18 FieldNames []string 19 Fields map[string]string 20 Errors map[string]string 21 } 22 23 func DisplayUploadImageForm(w http.ResponseWriter, r *http.Request, u *UploadImageForm) { 24 RenderGatedTemplate(w, WebAppRoot+"/templates/uploadimageform.html", u) 25 } 26 27 func ProcessUploadImage(w http.ResponseWriter, r *http.Request, u *UploadImageForm) { 28 29 shouldProcessThumbnailAsynchronously := true 30 31 file, fileheader, err := r.FormFile("imagefile") 32 33 if err != nil { 34 log.Println("Encountered error when attempting to read uploaded file: ", err) 35 } 36 37 randomFileName := utility.GenerateUUID() 38 39 if fileheader != nil { 40 41 extension := filepath.Ext(fileheader.Filename) 42 r.ParseMultipartForm(32 << 20) 43 44 defer file.Close() 45 46 imageFilePathWithoutExtension := "./static/uploads/images/" + randomFileName 47 f, err := os.OpenFile(imageFilePathWithoutExtension+extension, os.O_WRONLY|os.O_CREATE, 0666) 48 49 if err != nil { 50 log.Println(err) 51 return 52 } 53 54 defer f.Close() 55 io.Copy(f, file) 56 57 // Note: Moved the thumbnail generation logic (commented out code block below) to the 58 // ImageResizeTask object in the tasks package. 59 thumbnailResizeTask := tasks.NewImageResizeTask(imageFilePathWithoutExtension, extension) 60 61 if shouldProcessThumbnailAsynchronously == true { 62 63 asyncq.TaskQueue <- thumbnailResizeTask 64 65 } else { 66 67 thumbnailResizeTask.Perform() 68 } 69 70 m := make(map[string]string) 71 m["thumbnailPath"] = strings.TrimPrefix(imageFilePathWithoutExtension, ".") + "_thumb.png" 72 m["imagePath"] = strings.TrimPrefix(imageFilePathWithoutExtension, ".") + ".png" 73 m["PageTitle"] = "Image Preview" 74 75 RenderGatedTemplate(w, WebAppRoot+"/templates/imagepreview.html", m) 76 77 } else { 78 w.Write([]byte("Failed to process uploaded file!")) 79 } 80 } 81 82 func ValidateUploadImageForm(w http.ResponseWriter, r *http.Request, u *UploadImageForm) { 83 84 ProcessUploadImage(w, r, u) 85 86 } 87 88 func UploadImageHandler(w http.ResponseWriter, r *http.Request) { 89 90 u := UploadImageForm{} 91 u.Fields = make(map[string]string) 92 u.Errors = make(map[string]string) 93 u.PageTitle = "Upload Image" 94 95 switch r.Method { 96 97 case "GET": 98 DisplayUploadImageForm(w, r, &u) 99 case "POST": 100 ValidateUploadImageForm(w, r, &u) 101 default: 102 DisplayUploadImageForm(w, r, &u) 103 } 104 105 }