forked from GoAdminGroup/go-admin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
file_upload.go
98 lines (83 loc) · 2.23 KB
/
file_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
package action
import (
"html/template"
"github.com/romutchio/go-admin/context"
"github.com/romutchio/go-admin/modules/constant"
"github.com/romutchio/go-admin/template/types"
)
type FileUploadAction struct {
BaseAction
Url string
Method string
FileName string
Handlers []context.Handler
}
func FileUpload(id string, handler types.Handler) *FileUploadAction {
if id == "" {
panic("wrong file upload action parameter, empty id")
}
return &FileUploadAction{
Url: URL(id),
Method: "post",
FileName: "file",
Handlers: context.Handlers{handler.Wrap()},
}
}
func (file *FileUploadAction) SetUrl(url string) *FileUploadAction {
file.Url = url
return file
}
func (file *FileUploadAction) SetMethod(method string) *FileUploadAction {
file.Method = method
return file
}
func (file *FileUploadAction) GetCallbacks() context.Node {
return context.Node{
Path: file.Url,
Method: file.Method,
Handlers: file.Handlers,
Value: map[string]interface{}{constant.ContextNodeNeedAuth: 1},
}
}
func (file *FileUploadAction) Js() template.JS {
return template.JS(`$('` + file.BtnId + `').on('click', function(){
$('` + file.BtnId + `_input').click();
});
$("` + file.BtnId + `_input").on("change", function () {
var files = $('` + file.BtnId + `_input').prop('files');
var data = new FormData();
data.append('` + file.FileName + `', files[0]);
NProgress.start();
$.ajax({
url: '` + file.Url + `',
type: '` + file.Method + `',
data: data,
cache: false,
processData: false,
contentType: false,
success: function (data) {
NProgress.done();
if (data.code === 0) {
swal(data.msg, '', 'success');
$.pjax.reload('#pjax-container');
} else {
swal(data.msg, '', 'error');
}
},
error: function (data) {
NProgress.done();
if (data.responseText !== "") {
swal(data.responseJSON.msg, '', 'error');
} else {
swal('error', '', 'error');
}
},
});
});`)
}
func (file *FileUploadAction) BtnAttribute() template.HTML {
return template.HTML(`href="javascript:;"`)
}
func (file *FileUploadAction) FooterContent() template.HTML {
return template.HTML(`<input class="` + file.BtnId[1:] + `_input" type="file" multiple="multiple" style="display:none" />`)
}