-
Notifications
You must be signed in to change notification settings - Fork 2
/
FileUploadv2.go
94 lines (83 loc) · 2.46 KB
/
FileUploadv2.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
package main
import (
"crypto/rand"
"fmt"
"io/ioutil"
"log"
"mime"
"net/http"
"os"
"path/filepath"
)
const maxUploadSize = 1024 * 1024 * 1024 // not 2 mb
const uploadPath = "./tmp"
func main() {
http.HandleFunc("/upload", uploadFileHandler())
fs := http.FileServer(http.Dir(uploadPath))
http.Handle("/files/", http.StripPrefix("/files", fs))
log.Print("Server started on localhost:8080, use /upload for uploading files and /files/{fileName} for downloading")
log.Fatal(http.ListenAndServe(":8080", nil))
}
func uploadFileHandler() http.HandlerFunc {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// validate file size
r.Body = http.MaxBytesReader(w, r.Body, maxUploadSize)
if err := r.ParseMultipartForm(maxUploadSize); err != nil {
renderError(w, "FILE_TOO_BIG", http.StatusBadRequest)
return
}
// parse and validate file and post parameters
fileType := r.PostFormValue("type")
file, _, err := r.FormFile("uploadFile")
if err != nil {
renderError(w, "INVALID_FILE", http.StatusBadRequest)
return
}
defer file.Close()
fileBytes, err := ioutil.ReadAll(file)
if err != nil {
renderError(w, "INVALID_FILE", http.StatusBadRequest)
return
}
// check file type, detectcontenttype only needs the first 512 bytes
filetype := http.DetectContentType(fileBytes)
switch filetype {
case "image/jpeg", "image/jpg":
case "image/gif", "image/png":
case "application/pdf":
break
default:
renderError(w, "INVALID_FILE_TYPE", http.StatusBadRequest)
return
}
fileName := randToken(12)
fileEndings, err := mime.ExtensionsByType(fileType)
if err != nil {
renderError(w, "CANT_READ_FILE_TYPE", http.StatusInternalServerError)
return
}
newPath := filepath.Join(uploadPath, fileName+fileEndings[0])
fmt.Printf("FileType: %s, File: %s\n", fileType, newPath)
// write file
newFile, err := os.Create(newPath)
if err != nil {
renderError(w, "CANT_WRITE_FILE", http.StatusInternalServerError)
return
}
defer newFile.Close() // idempotent, okay to call twice
if _, err := newFile.Write(fileBytes); err != nil || newFile.Close() != nil {
renderError(w, "CANT_WRITE_FILE", http.StatusInternalServerError)
return
}
w.Write([]byte("SUCCESS"))
})
}
func renderError(w http.ResponseWriter, message string, statusCode int) {
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(message))
}
func randToken(len int) string {
b := make([]byte, len)
rand.Read(b)
return fmt.Sprintf("%x", b)
}