/
upload.go
152 lines (133 loc) · 3.47 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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
package goup
import (
"encoding/json"
"errors"
"fmt"
"io"
"log"
"mime/multipart"
"net/http"
"os"
"path"
"path/filepath"
"time"
"github.com/bingoohuang/gg/pkg/man"
"github.com/segmentio/ksuid"
)
// WriteJSON writes the JSON of v to http.ResponseWriter.
func WriteJSON(w http.ResponseWriter, v interface{}) error {
js, err := json.Marshal(v)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
_, err = w.Write(js)
return err
}
// UploadResult is the structure of download result.
type UploadResult struct {
Files []string
FileSizes []string
TotalSize string
Cost string
Start string
End string
MaxTempMemory string
LimitSize string
}
// NetHTTPUpload upload
func NetHTTPUpload(w http.ResponseWriter, r *http.Request, rootDir string, limitSize uint64) error {
start := time.Now()
maxMemory := 16 /*16 MiB */ << 20
if err := r.ParseMultipartForm(int64(maxMemory)); err != nil {
return err
}
totalSize := int64(0)
fileCount := len(r.MultipartForm.File)
index := 0
var files []string
var fileSizes []string
for k, v := range r.MultipartForm.File {
index++
file, n, err := saveFormFile(v[0], rootDir, r.URL.Path, index, fileCount)
if err != nil {
return err
}
totalSize += n
files = append(files, file)
fileSizes = append(fileSizes, man.Bytes(uint64(n)))
log.Printf("recieved file %s: %s", k, file)
}
end := time.Now()
return WriteJSON(w, UploadResult{
Start: start.UTC().Format(http.TimeFormat),
End: end.UTC().Format(http.TimeFormat),
Files: files,
FileSizes: fileSizes,
MaxTempMemory: man.Bytes(uint64(maxMemory)),
LimitSize: man.Bytes(limitSize),
TotalSize: man.Bytes(uint64(totalSize)),
Cost: end.Sub(start).String(),
})
}
// ParseFormFile returns the first file for the provided form key.
// FormFile calls ParseMultipartForm and ParseForm if necessary.
func ParseFormFile(m *multipart.Form) (*multipart.FileHeader, error) {
if m != nil {
if fhs := m.File["file"]; len(fhs) > 0 {
return fhs[0], nil
}
for _, v := range m.File {
return v[0], nil
}
}
return nil, ErrMissingFile
}
// ErrMissingFile may be returned from FormFile when the is no uploaded file.
var ErrMissingFile = errors.New("there is no uploaded file")
// TrimExt trim ext from the right of filepath.
func TrimExt(filepath, ext string) string {
return filepath[:len(filepath)-len(ext)]
}
func saveFormFile(fh *multipart.FileHeader, rootDir, urlPath string, fileIndex, fileCount int) (string, int64, error) {
file, err := fh.Open()
if err != nil {
return "", 0, err
}
base := filepath.Base(urlPath)
if base != "/" {
if fileCount > 1 {
ext := path.Ext(base)
base = fmt.Sprintf("%s.%d%s", TrimExt(base, ext), fileIndex, ext)
}
}
filename := firstFilename(base, filepath.Base(fh.Filename), ksuid.New().String())
fullPath := filepath.Join(rootDir, filename)
// use temporary file directly
if f, ok := file.(*os.File); ok {
n, err := file.Seek(0, io.SeekEnd)
if err != nil {
return "", n, err
}
if err := file.Close(); err != nil {
return "", 0, err
}
if err := os.Rename(f.Name(), fullPath); err != nil {
return "", 0, err
}
return fullPath, n, nil
}
n, err := writeChunk(fullPath, nil, file, nil)
if err := file.Close(); err != nil {
return "", 0, err
}
return fullPath, n, err
}
func firstFilename(s ...string) string {
for _, i := range s {
if i != "" && i != "/" {
return i
}
}
return ""
}