forked from leon-richardt/jaf
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathuploadhandler.go
More file actions
87 lines (68 loc) · 1.75 KB
/
Copy pathuploadhandler.go
File metadata and controls
87 lines (68 loc) · 1.75 KB
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 main
import (
"io"
"log"
"math/rand"
"mime/multipart"
"net/http"
"os"
"strings"
)
type uploadHandler struct {
config *Config
}
func (h *uploadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
defer r.Body.Close()
uploadFile, header, err := r.FormFile("file")
if err != nil {
http.Error(w, "could not read uploaded file: "+err.Error(), http.StatusBadRequest)
log.Println(" could not read uploaded file: " + err.Error())
return
}
defer uploadFile.Close()
_, fileExtension := splitFileName(header.Filename)
// Find an unused file name
fileID := createRandomFileName(h.config.LinkLength)
for ; savedFileNames.Contains(fileID); fileID = createRandomFileName(h.config.LinkLength) {
}
fullFileName := fileID + fileExtension
savePath := h.config.FileDir + fullFileName
link := h.config.LinkPrefix + fullFileName
err = saveFile(uploadFile, savePath)
if err != nil {
http.Error(w, "could not save file: "+err.Error(), http.StatusInternalServerError)
log.Println(" could not save file: " + err.Error())
return
}
savedFileNames.Insert(fullFileName)
// Implicitly means code 200
w.Write([]byte(link))
}
func saveFile(data multipart.File, name string) error {
file, err := os.Create(name)
if err != nil {
return err
}
defer file.Close()
_, err = io.Copy(file, data)
if err != nil {
return err
}
return nil
}
func createRandomFileName(length int) string {
chars := make([]byte, length)
for i := 0; i < length; i++ {
index := rand.Intn(len(allowedChars))
chars[i] = allowedChars[index]
}
return string(chars)
}
func splitFileName(name string) (string, string) {
extIndex := strings.LastIndex(name, ".")
if extIndex == -1 {
// No dot at all
return name, ""
}
return name[:extIndex], name[extIndex:]
}