-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathupload.go
67 lines (57 loc) · 1.23 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
/* Title.png uploads */
package main
import (
"bytes"
"fmt"
"image/png"
"image/jpeg"
"io"
"log"
"net/http"
"os"
"path/filepath"
)
const filesizeLimit = 100 * 1024
func uploadHandler(w http.ResponseWriter, r *http.Request) {
// Check that the body is a PNG or JPEG file with a maximum of 100KB.
var buf bytes.Buffer
n, err := buf.ReadFrom(io.LimitReader(r.Body, filesizeLimit))
if err != nil {
w.WriteHeader(500)
fmt.Fprintln(w, err)
return
}
if n >= filesizeLimit {
w.WriteHeader(400)
fmt.Fprintln(w, "File too large.")
return
}
// First try PNG, then JPEG.
_, err = png.Decode(bytes.NewReader(buf.Bytes()))
if err != nil {
_, err = jpeg.Decode(bytes.NewReader(buf.Bytes()))
if err != nil {
w.WriteHeader(400)
fmt.Fprintln(w, "File not a PNG or JPEG image.")
return
}
}
path := uploadPrefix + r.URL.Path
os.MkdirAll(filepath.Dir(path), 0777)
out, err := os.Create(path)
if err != nil {
w.WriteHeader(500)
fmt.Fprintf(w, "Unable to create the file for writing.")
return
}
defer out.Close()
// write the content from POST to the file
_, err = io.Copy(out, &buf)
if err != nil {
w.WriteHeader(500)
fmt.Fprintln(w, err)
return
}
w.WriteHeader(200)
log.Println("->", path, "\t", n)
}