forked from gobuffalo/buffalo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile.go
82 lines (72 loc) · 1.61 KB
/
file.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
package binding
import (
"mime/multipart"
"net/http"
"reflect"
"github.com/pkg/errors"
)
// MaxFileMemory can be used to set the maximum size, in bytes, for files to be
// stored in memory during uploaded for multipart requests.
// See https://golang.org/pkg/net/http/#Request.ParseMultipartForm for more
// information on how this impacts file uploads.
var MaxFileMemory int64 = 5 * 1024 * 1024
// File holds information regarding an uploaded file
type File struct {
multipart.File
*multipart.FileHeader
}
// Valid if there is an actual uploaded file
func (f File) Valid() bool {
return f.File != nil
}
func (f File) String() string {
if f.File == nil {
return ""
}
return f.Filename
}
func init() {
sb := func(req *http.Request, i interface{}) error {
err := req.ParseMultipartForm(MaxFileMemory)
if err != nil {
return errors.WithStack(err)
}
if err := decoder.Decode(req.Form, i); err != nil {
return errors.WithStack(err)
}
form := req.MultipartForm.File
if len(form) == 0 {
return nil
}
ri := reflect.Indirect(reflect.ValueOf(i))
rt := ri.Type()
for n := range form {
f := ri.FieldByName(n)
if !f.IsValid() {
for i := 0; i < rt.NumField(); i++ {
sf := rt.Field(i)
if sf.Tag.Get("form") == n {
f = ri.Field(i)
break
}
}
}
if !f.IsValid() {
continue
}
if _, ok := f.Interface().(File); !ok {
continue
}
mf, mh, err := req.FormFile(n)
if err != nil {
return errors.WithStack(err)
}
f.Set(reflect.ValueOf(File{
File: mf,
FileHeader: mh,
}))
}
return nil
}
binders["multipart/form-data"] = sb
}