forked from carl-mastrangelo/pixur
-
Notifications
You must be signed in to change notification settings - Fork 1
/
upload.go
87 lines (76 loc) · 1.78 KB
/
upload.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
package handlers
import (
"encoding/hex"
"io/ioutil"
"mime/multipart"
"net/http"
"pixur.org/pixur/api"
"pixur.org/pixur/fe/server"
)
type upsertPicHandler struct {
c api.PixurServiceClient
pt *paths
}
func (h *upsertPicHandler) upsert(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
var filename string
var filedata multipart.File
if uploadedFile, fileHeader, err := r.FormFile(h.pt.pr.File()); err != nil {
if err != http.ErrMissingFile && err != http.ErrNotMultipart {
httpError(w, &HTTPErr{
Message: "can't read file: " + err.Error(),
Code: http.StatusBadRequest,
})
return
}
} else {
filename = fileHeader.Filename
filedata = uploadedFile
defer filedata.Close()
}
var md5Hash []byte
if hexHash := r.FormValue(h.pt.pr.Md5Hash()); hexHash != "" {
var err error
md5Hash, err = hex.DecodeString(hexHash)
if err != nil {
httpError(w, &HTTPErr{
Message: "can't decode md5 hash: " + err.Error(),
Code: http.StatusBadRequest,
})
return
}
}
var data []byte
if filedata != nil {
var err error
data, err = ioutil.ReadAll(filedata)
if err != nil {
httpError(w, &HTTPErr{
Message: "can't read file: " + err.Error(),
Code: http.StatusInternalServerError,
})
return
}
}
resp, sts := h.c.UpsertPic(ctx, &api.UpsertPicRequest{
Url: r.FormValue(h.pt.pr.Url()),
Name: filename,
Data: data,
Md5Hash: md5Hash,
})
if sts != nil {
httpError(w, sts)
return
}
http.Redirect(w, r, h.pt.Viewer(resp.Pic.Id).String(), http.StatusSeeOther)
}
func init() {
register(func(s *server.Server) error {
h := upsertPicHandler{
c: s.Client,
pt: &paths{r: s.HTTPRoot},
}
s.HTTPMux.Handle(h.pt.UpsertPicAction().Path, newActionHandler(s, http.HandlerFunc(h.upsert)))
return nil
})
}