forked from uadmin/uadmin
-
Notifications
You must be signed in to change notification settings - Fork 0
/
process_upload.go
306 lines (273 loc) · 8.01 KB
/
process_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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
package uadmin
import (
"context"
"encoding/base64"
"fmt"
"github.com/sirupsen/logrus"
"image"
"image/gif"
"image/jpeg"
"image/png"
"io"
"net/http"
"os"
"path"
"strings"
"github.com/nfnt/resize"
)
// GetImageSizer can be inplemented for any model to customize the image size uploaded
// to that model
type GetImageSizer interface {
GetImageSize() (int, int)
}
func processUpload(r *http.Request, f *F, modelName string, session *Session, s *ModelSchema) (val string) {
base64Format := false
// Get file description from http request
httpFile, handler, err := r.FormFile(f.Name)
if r.Context().Value(CKey("dAPI")) != nil {
httpFile, handler, err = r.FormFile(f.ColumnName)
}
if err != nil {
if r.Form.Get(f.Name+"-raw") != "" {
base64Format = true
} else {
return ""
}
} else {
defer httpFile.Close()
}
// return "", s if there is no file uploaded
if !base64Format {
if handler.Filename == "" {
return ""
}
}
if base64Format {
filesize := float64(len(r.Form.Get(f.Name+"-raw"))-strings.Index(r.Form.Get(f.Name+"-raw"), "://")) * 0.75
if int64(filesize) > MaxUploadFileSize {
f.ErrMsg = fmt.Sprintf("File is too large. Maximum upload file size is: %d Mb", MaxUploadFileSize/1024/1024)
return ""
}
} else {
if handler.Size > MaxUploadFileSize {
f.ErrMsg = fmt.Sprintf("File is too large. Maximum upload file size is: %d Mb", MaxUploadFileSize/1024/1024)
return ""
}
}
// Get the upload to path and create it if it doesn't exist
uploadTo := "/media/" + f.Type + "s/"
if f.UploadTo != "" {
uploadTo = f.UploadTo
}
if _, err = os.Stat("." + uploadTo); os.IsNotExist(err) {
err = os.MkdirAll("."+uploadTo, os.ModePerm)
if err != nil {
Trail(ERROR, "processForm.MkdirAll. %s", err)
return ""
}
}
// Generate local file name and create it
var fName string
var pathName string
var fParts []string
if base64Format {
fName = r.Form.Get(f.Name + "-raw")[0:strings.Index(r.Form.Get(f.Name+"-raw"), "://")]
fParts = strings.Split(fName, ".")
} else {
fName = handler.Filename
fName = strings.Replace(fName, "/", "_", -1)
fName = strings.Replace(fName, "\\", "_", -1)
fName = strings.Replace(fName, "..", "_", -1)
fParts = strings.Split(fName, ".")
}
fExt := strings.ToLower(fParts[len(fParts)-1])
pathName = "." + uploadTo + modelName + "_" + f.Name + "_" + GenerateBase64(10) + "/"
if (f.Type == cIMAGE || f.Type == cIMAGE_MINIO) && len(fParts) > 1 {
fName = strings.TrimSuffix(fName, "."+fExt) + "_raw." + fExt
} else if f.Type == cIMAGE || f.Type == cIMAGE_MINIO {
f.ErrMsg = "Image file with no extension. Please use png, jpg, jpeg or gif."
return ""
}
for _, err = os.Stat(pathName + fName); os.IsExist(err); {
pathName = "." + uploadTo + modelName + "_" + f.Name + "_" + GenerateBase64(10) + "/"
}
// Sanitize the file name
fName = pathName + path.Clean(fName)
err = os.MkdirAll(pathName, os.ModePerm)
if err != nil {
Trail(ERROR, "processForm.MkdirAll. unable to create folder for uploaded file. %s", err)
return ""
}
fRaw, err := os.OpenFile(fName, os.O_WRONLY|os.O_CREATE, DefaultMediaPermission)
if err != nil {
Trail(ERROR, "processForm.OpenFile. unable to create file. %s", err)
return ""
}
// Copy http file to local
if base64Format {
data, err := base64.StdEncoding.DecodeString(r.Form.Get(f.Name + "-raw")[strings.Index(r.Form.Get(f.Name+"-raw"), "://")+3 : len(r.Form.Get(f.Name+"-raw"))])
if err != nil {
Trail(ERROR, "ProcessForm error decoding base64. %s", err)
return ""
}
_, err = fRaw.Write(data)
if err != nil {
Trail(ERROR, "ProcessForm error writing file. %s", err)
return ""
}
} else {
_, err = io.Copy(fRaw, httpFile)
if err != nil {
Trail(ERROR, "ProcessForm error uploading http file. %s", err)
return ""
}
}
fRaw.Close()
// store the file path to DB
if f.Type == cFILE {
val = fmt.Sprint(strings.TrimPrefix(fName, "."))
} else {
// If case it is an image, process it first
fRaw, err = os.Open(fName)
if err != nil {
Trail(ERROR, "ProcessForm.Open %s", err)
return ""
}
// decode jpeg,png,gif into image.Image
var img image.Image
if fExt == cJPG || fExt == cJPEG {
img, err = jpeg.Decode(fRaw)
} else if fExt == cPNG {
img, err = png.Decode(fRaw)
} else if fExt == cGIF {
img, err = gif.Decode(fRaw)
} else {
f.ErrMsg = "Unknown image file extension. Please use, png, jpg/jpeg or gif"
return ""
}
if err != nil {
f.ErrMsg = "Unknown image format or image corrupted."
Trail(WARNING, "ProcessForm.Decode %s", err)
return ""
}
// Resize the image to fit max height, max width
width := img.Bounds().Dx()
height := img.Bounds().Dy()
model, _ := NewModel(modelName, false)
// Check if there is a custom image size
if sizer, ok := model.Interface().(GetImageSizer); ok || height > MaxImageHeight {
if ok {
height, width = sizer.GetImageSize()
} else {
Ratio := float64(MaxImageHeight) / float64(height)
width = int(float64(width) * Ratio)
height = int(float64(height) * Ratio)
if width > MaxImageWidth {
Ratio = float64(MaxImageWidth) / float64(width)
width = int(float64(width) * Ratio)
height = int(float64(height) * Ratio)
}
}
img = resize.Resize(uint(width), uint(height), img, resize.Lanczos3)
}
// Store the active file
fActiveName := strings.Replace(fName, "_raw", "", -1)
fActive, err := os.Create(fActiveName)
if err != nil {
Trail(ERROR, "ProcessForm.Create unable to create file for resized image. %s", err)
return ""
}
defer fActive.Close()
fRaw, err = os.OpenFile(fName, os.O_WRONLY, 0644)
if err != nil {
Trail(ERROR, "ProcessForm.Open %s", err)
return ""
}
defer fRaw.Close()
// write new image to file
if fExt == cJPG || fExt == cJPEG {
//if f.Type == cIMAGE_MINIO {
ctx := context.Background()
minioConfig := NewMinioConfig("", "", "", false, "", "", "", false)
minioService, err := NewMinioService(ctx, minioConfig)
if err != nil {
logrus.Error(err)
return ""
}
minioFilename, err := minioService.UploadFile(ctx, handler.Filename, "application/jpeg", handler.Size, httpFile)
if err != nil {
logrus.Error(err)
return ""
}
return minioFilename
//}
//var buf bytes.Buffer
//err = jpeg.Encode(&buf, img, nil)
//if err != nil {
// Trail(ERROR, "ProcessForm.Encode active jpg. %s", err)
// return ""
//}
//
//return toBase64(buf.Bytes())
//err = jpeg.Encode(fRaw, img, nil)
//if err != nil {
// Trail(ERROR, "ProcessForm.Encode raw jpg. %s", err)
// return ""
//}
}
if fExt == cPNG {
//if f.Type == cIMAGE_MINIO {
ctx := context.Background()
minioConfig := NewMinioConfig("", "", "", false, "", "", "", false)
minioService, err := NewMinioService(ctx, minioConfig)
if err != nil {
logrus.Error(err)
return ""
}
minioFilename, err := minioService.UploadFile(ctx, handler.Filename, "application/png", handler.Size, httpFile)
if err != nil {
logrus.Error(err)
return ""
}
return minioFilename
//}
//var buf bytes.Buffer
//err = png.Encode(&buf, img)
//if err != nil {
// Trail(ERROR, "ProcessForm.Encode active png. %s", err)
// return ""
//}
//
//return toBase64(buf.Bytes())
//err = png.Encode(fRaw, img)
//if err != nil {
// Trail(ERROR, "ProcessForm.Encode raw png. %s", err)
// return ""
//}
}
if fExt == cGIF {
o := gif.Options{}
err = gif.Encode(fActive, img, &o)
if err != nil {
Trail(ERROR, "ProcessForm.Encode active gif. %s", err)
return ""
}
err = gif.Encode(fRaw, img, &o)
if err != nil {
Trail(ERROR, "ProcessForm.Encode raw gif. %s", err)
return ""
}
}
val = fmt.Sprint(strings.TrimPrefix(fActiveName, "."))
}
// Delete old file if it exists and there not required
if !RetainMediaVersions {
oldFileName := "." + fmt.Sprint(f.Value)
oldFileParts := strings.Split(oldFileName, "/")
os.RemoveAll(strings.Join(oldFileParts[0:len(oldFileParts)-1], "/"))
}
return val
}
func toBase64(data []byte) string {
return base64.StdEncoding.EncodeToString(data)
}