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