-
Notifications
You must be signed in to change notification settings - Fork 36
/
Copy pathstorage.go
669 lines (561 loc) · 16.6 KB
/
storage.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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
package quark
import (
"bytes"
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"fmt"
"image"
_ "image/gif"
_ "image/jpeg"
_ "image/png"
"io"
"os"
"strconv"
"strings"
"github.com/aliyun/aliyun-oss-go-sdk/oss"
"github.com/gabriel-vasile/mimetype"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"github.com/quarkcloudio/quark-go/v3/utils/file"
"github.com/quarkcloudio/quark-go/v3/utils/rand"
)
var (
OssStorage = "oss"
LocalStorage = "local"
MinioStorage = "minio"
)
// OSS配置
type OSSConfig struct {
Endpoint string // OSS endpoint
AccessKeyID string // AccessId
AccessKeySecret string // AccessKey
BucketName string // BucketName
Domain string // OSS自定义域名
}
// Minio配置
type MinioConfig struct {
Endpoint string // Endpoint
AccessKeyID string // AccessKeyID
AccessKeySecret string // AccessKey
SecretAccessKey string // SecretAccessKey
UseSSL bool // UseSSL
BucketName string // BucketName
Domain string // OSS自定义域名
}
// 配置
type StorageConfig struct {
LimitSize int64 // 限制文件大小
LimitType []string // 限制文件类型
LimitImageWidth int // 限制图片宽度
LimitImageHeight int // 限制图片高度
Driver string // 存储驱动
SavePath string // 保存路径
SaveName string // 保存文件名称
SaveRandName bool // 随机保存文件名称
CheckFileExist bool // 检测文件是否已存在
OSSConfig *OSSConfig // OSS配置
MinioConfig *MinioConfig // Minio配置
}
// 对照表
var ContentTypeList = map[string]string{
"application/x-dosexec": "exe",
"application/msword": "doc",
"application/vnd.ms-excel": "xls",
"application/x-xls": "xls",
"application/vnd.ms-powerpoint": "ppt",
"application/x-ppt": "ppt",
"application/x-dmg": "dmg",
"application/x-gzip": "gz",
"application/x-rar": "rar",
"application/x-tar": "tar",
"application/x-xar": "pkg",
"application/x-rpm": "rpm",
"application/x-stuffit": "sif",
"application/x-archive": "",
"application/x-arc": "arc",
"application/x-eet": "eet",
"application/x-zoo": "zoo",
"application/x-lz4": "lz4",
"application/x-lrzip": "lrz",
"application/x-lzh": "lzh",
"application/warc": "warc",
"application/x-7z-compressed": "7z",
"application/x-xz": "xz",
"application/x-lha": "lha",
"application/x-arj": "arj",
"application/x-cpio": "cpio",
"application/x-compress": "",
"application/x-lzma": "",
"application/zip": "zip",
"application/vnd.ms-cab-compressed": "cab",
"application/pdf": "pdf",
"application/vnd.openxmlformats-officedocument.wordprocessingml.document": "docx",
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": "xlsx",
"application/vnd.openxmlformats-officedocument.presentationml.presentation": "pptx",
"application/font-woff": "woff",
"application/x-font-ttf": "ttf",
"application/vnd.ms-fontobject": "eot",
"application/x-font-sfn": "",
"application/vnd.ms-opentype": "otf",
"application/x-mif": "mif",
"application/vnd.font-fontforge-sfd": "sfd",
"audio/mpeg": "mp3",
"audio/x-m4a": "m4a",
"audio/x-wav": "wav",
"image/tiff": "tiff",
"image/gif": "gif",
"image/jpeg": "jpg",
"image/x-ms-bmp": "bmp",
"image/x-icon": "ico",
"image/svg+xml": "svg",
"image/x-cursor": "cur",
"image/vnd.adobe.photoshop": "pnd",
"image/png": "png",
"text/html": "html",
"text/plain": "txt",
"text/json": "json",
"text/rtf": "rtf",
"application/xml": "xml",
"text/rss": "rss",
"application/java-archive": "jar",
"application/x-java-applet": "jar",
"application/x-shockwave-flash": "swf",
"application/pkcs7-signature": "p7",
"application/x-pem": "pem",
"application/x-java-jnlp-file": "jnlp",
"application/vnd.tcpdump.pcap": "pcap",
"text/x-shellscript": "sh",
"text/x-perl": "pl",
"text/x-ruby": "rb",
"text/x-python": "py",
"text/x-awk": "awk",
"text/x-lua": "lua",
"application/javascript": "js",
"text/x-php": "php",
"application/x-executable": "",
"application/x-coredump": "core",
"video/x-flv": "flv",
"video/x-fli": "fli",
"video/x-flc": "flc",
"video/mj2": "mj2",
"video/x-mng": "mng",
"video/x-jng": "jng",
"video/mpeg": "mpg",
"video/mpv": "mpv",
"video/h264": "264",
"video/webm": "webm",
"video/matroska": "mkv",
"vidoe/x-sgi-movie": "sgi",
"video/quicktime": "qt",
"video/mp4": "mp4",
"video/3gpp": "3gp",
}
// 文件结构体
type File struct {
Header map[string][]string // map[Content-Disposition:[form-data; name="file"; filename="demo.jpg"] Content-Type:[image/jpeg]]
Name string // 文件名称
Size int64 // 文件大小
Ext string // 文件扩展名
ContentType string // 文件类型
Content []byte // 文件内容
Hash string // 文件哈希值
Extra interface{} // 文件扩展信息
}
// 文件信息
type FileInfo struct {
Name string `json:"name"` // 文件名称
Size int64 `json:"size"` // 文件大小
Ext string `json:"ext"` // 文件扩展名
ContentType string `json:"contentType"` // 文件类型
Path string `json:"path"` // 上传路径
Url string `json:"url"` // Url路径
Hash string `json:"hash"` // 文件哈希值
Extra interface{} `json:"extra"` // 文件扩展信息
}
// 结构体
type FileSystem struct {
Config *StorageConfig // 配置信息
File *File // 文件信息
}
// 初始化对象
func NewStorage(config *StorageConfig) *FileSystem {
if config.Driver == "" {
config.Driver = LocalStorage
}
return &FileSystem{
Config: config,
}
}
// 设置文件信息
func (p *FileSystem) Reader(file *File) *FileSystem {
if file.Size == 0 {
file.Size = int64(len(file.Content))
}
if file.ContentType == "" {
if file.Header != nil {
if len(file.Header["Content-Type"]) > 0 {
file.ContentType = file.Header["Content-Type"][0]
}
} else {
file.ContentType = mimetype.Detect(file.Content).String()
}
}
p.File = file
return p
}
// 设置文件标头
func (p *FileSystem) FileHeader(fileHeader map[string][]string) *FileSystem {
p.File.Header = fileHeader
return p
}
// 设置文件名称
func (p *FileSystem) FileName(fileName string) *FileSystem {
p.File.Name = fileName
return p
}
// 设置二进制内容
func (p *FileSystem) FileContent(fileContent []byte) *FileSystem {
p.File.Content = fileContent
return p
}
// 限制文件大小
func (p *FileSystem) LimitSize(limitSize int64) *FileSystem {
p.Config.LimitSize = limitSize
return p
}
// 限制文件类型
func (p *FileSystem) LimitType(limitType []string) *FileSystem {
p.Config.LimitType = limitType
return p
}
// 限制图片宽度
func (p *FileSystem) LimitImageWidth(limitImageWidth int) *FileSystem {
p.Config.LimitImageWidth = limitImageWidth
return p
}
// 限制图片高度
func (p *FileSystem) LimitImageHeight(limitImageHeight int) *FileSystem {
p.Config.LimitImageHeight = limitImageHeight
return p
}
// 读取图片宽高
func (p *FileSystem) WithImageExtra() *FileSystem {
byteReader := bytes.NewReader(p.File.Content)
imageConfig, _, err := image.DecodeConfig(byteReader)
if err != nil {
fmt.Println(err)
return p
}
p.File.Extra = map[string]interface{}{
"width": imageConfig.Width,
"height": imageConfig.Height,
}
return p
}
// 检测文件是否已存在
func (p *FileSystem) CheckFileExist() *FileSystem {
p.Config.CheckFileExist = true
return p
}
// 存储驱动
func (p *FileSystem) Driver(driver string) *FileSystem {
p.Config.Driver = driver
return p
}
// 保存路径
func (p *FileSystem) Path(path string) *FileSystem {
p.Config.SavePath = path
return p
}
// 随机保存文件名称
func (p *FileSystem) RandName() *FileSystem {
p.Config.SaveRandName = true
return p
}
// 保存文件名称
func (p *FileSystem) Name(name string) *FileSystem {
p.Config.SaveName = name
return p
}
// 计算文件哈希值
func (p *FileSystem) GetFileHash() (string, error) {
var (
hashValue string
err error
)
sha256New := sha256.New()
byteReader := bytes.NewReader(append(p.File.Content, []byte(p.File.Name)...))
_, err = io.Copy(sha256New, byteReader)
if err != nil {
return hashValue, err
}
hashValue = hex.EncodeToString(sha256New.Sum(nil))
return hashValue, nil
}
// 检查文件大小
func (p *FileSystem) checkFileSize() error {
var err error
if p.Config.LimitSize == 0 {
return err
}
if p.File.Size > p.Config.LimitSize {
err = errors.New("上传文件大小超出限制!")
}
return err
}
// 检查文件类型
func (p *FileSystem) checkFileType() error {
var (
err error
checkReuslt bool
limitText string
)
if len(p.Config.LimitType) == 0 {
return err
}
for _, v := range p.Config.LimitType {
if v == p.File.ContentType {
checkReuslt = true
}
// 获取允许上传文件的扩展名
allowFileExt := ContentTypeList[v]
if allowFileExt == "" {
allowFileExt = v
}
limitText = limitText + "," + allowFileExt
}
limitText = strings.Trim(limitText, ",")
if !checkReuslt {
return errors.New("文件类型 " + p.File.ContentType + " 不合法," + "请上传 " + limitText + " 格式的文件")
}
return err
}
// 检查图片文件宽高
func (p *FileSystem) checkImageWH() error {
var err error
if p.Config.LimitImageHeight == 0 || p.Config.LimitImageWidth == 0 {
return err
}
byteReader := bytes.NewReader(p.File.Content)
imageConfig, _, err := image.DecodeConfig(byteReader)
if err != nil {
return err
}
if imageConfig.Width != p.Config.LimitImageWidth || imageConfig.Height != p.Config.LimitImageHeight {
limitW := strconv.Itoa(p.Config.LimitImageWidth)
limitH := strconv.Itoa(p.Config.LimitImageHeight)
err = errors.New("请上传 " + limitW + "*" + limitH + " 尺寸的图片")
}
return err
}
// 检测文件合法性
func (p *FileSystem) CheckFile() error {
var err error
err = p.checkFileSize()
if err != nil {
return err
}
err = p.checkFileType()
if err != nil {
return err
}
err = p.checkImageWH()
if err != nil {
return err
}
return err
}
// 保存文件到本地
func (p *FileSystem) SaveToLocal() error {
savePath := p.Config.SavePath
if savePath == "" {
return errors.New("请设置保存路径")
}
if p.Config.SaveName == "" {
p.Config.SaveName = p.File.Name
}
// 获取文件扩展名
fileExt := ContentTypeList[p.File.ContentType]
if fileExt == "" {
return errors.New("无法获取文件扩展名!")
}
p.File.Ext = fileExt
// 检查文件合法性
err := p.CheckFile()
if err != nil {
return err
}
if p.Config.SaveRandName {
p.Config.SaveName = rand.MakeAlphanumeric(40) + "." + p.File.Ext
}
if !file.IsExist(savePath) {
err := os.MkdirAll(savePath, os.ModeDir)
if err != nil {
return err
}
}
saveName := p.Config.SaveName
if p.Config.CheckFileExist {
if file.IsExist(savePath + saveName) {
return errors.New("文件已存在:" + savePath + saveName)
}
}
// 计算文件哈希值
fileHash, err := p.GetFileHash()
if err != nil {
return err
}
p.File.Hash = fileHash
f, err := os.OpenFile(savePath+saveName, os.O_WRONLY|os.O_CREATE, 0666) //根据文件名创建文件路径
if err != nil {
return err
}
defer f.Close()
byteReader := bytes.NewReader(p.File.Content)
io.Copy(f, byteReader)
return nil
}
// 保存文件到OSS
func (p *FileSystem) SaveToOSS() error {
if p.Config.OSSConfig == nil {
return errors.New("请配置OSS信息")
}
savePath := p.Config.SavePath
if savePath == "" {
return errors.New("请设置保存路径")
}
if p.Config.SaveName == "" {
p.Config.SaveName = p.File.Name
}
// 获取文件扩展名
fileExt := ContentTypeList[p.File.ContentType]
if fileExt == "" {
return errors.New("无法获取文件扩展名!")
}
p.File.Ext = fileExt
// 检查文件合法性
err := p.CheckFile()
if err != nil {
return err
}
if p.Config.SaveRandName {
p.Config.SaveName = rand.MakeAlphanumeric(40) + "." + p.File.Ext
}
saveName := p.Config.SaveName
// 计算文件哈希值
fileHash, err := p.GetFileHash()
if err != nil {
return err
}
p.File.Hash = fileHash
client, err := oss.New(p.Config.OSSConfig.Endpoint, p.Config.OSSConfig.AccessKeyID, p.Config.OSSConfig.AccessKeySecret)
if err != nil {
return err
}
bucket, err := client.Bucket(p.Config.OSSConfig.BucketName)
if err != nil {
return err
}
// 指定Object访问权限
objectAcl := oss.ObjectACL(oss.ACLPublicRead)
byteReader := bytes.NewReader(p.File.Content)
err = bucket.PutObject(savePath+saveName, byteReader, objectAcl)
if err != nil {
return err
}
return nil
}
// 保存文件到Minio
func (p *FileSystem) SaveToMinio() error {
if p.Config.MinioConfig == nil {
return errors.New("请配置Minio信息")
}
savePath := p.Config.SavePath
if savePath == "" {
return errors.New("请设置保存路径")
}
if p.Config.SaveName == "" {
p.Config.SaveName = p.File.Name
}
// 获取文件扩展名
fileExt := ContentTypeList[p.File.ContentType]
if fileExt == "" {
return errors.New("无法获取文件扩展名!")
}
p.File.Ext = fileExt
// 检查文件合法性
err := p.CheckFile()
if err != nil {
return err
}
if p.Config.SaveRandName {
p.Config.SaveName = rand.MakeAlphanumeric(40) + "." + p.File.Ext
}
saveName := p.Config.SaveName
// 计算文件哈希值
fileHash, err := p.GetFileHash()
if err != nil {
return err
}
p.File.Hash = fileHash
ctx := context.Background()
// Initialize minio client object.
minioClient, err := minio.New(p.Config.MinioConfig.Endpoint, &minio.Options{
Creds: credentials.NewStaticV4(p.Config.MinioConfig.AccessKeyID, p.Config.MinioConfig.SecretAccessKey, ""),
Secure: p.Config.MinioConfig.UseSSL,
})
if err != nil {
return err
}
byteReader := bytes.NewReader(p.File.Content)
// Upload the zip file with FPutObject
info, err := minioClient.PutObject(ctx, p.Config.MinioConfig.BucketName, saveName, byteReader, -1, minio.PutObjectOptions{ContentType: p.File.ContentType})
if err != nil {
return err
}
fmt.Printf("Successfully uploaded %s of size %d\n", saveName, info.Size)
return nil
}
// 保存文件
func (p *FileSystem) Save() (fileInfo *FileInfo, err error) {
var fileUrl = ""
switch p.Config.Driver {
case LocalStorage:
err = p.SaveToLocal()
if err != nil {
return fileInfo, err
}
fileUrl = p.Config.SavePath + p.Config.SaveName
case OssStorage:
err = p.SaveToOSS()
if err != nil {
return fileInfo, err
}
if p.Config.OSSConfig.Domain != "" {
fileUrl = "//" + p.Config.OSSConfig.Domain + "/" + p.Config.SavePath + p.Config.SaveName
} else {
fileUrl = "//" + p.Config.OSSConfig.BucketName + "." + p.Config.OSSConfig.Endpoint + "/" + p.Config.SavePath + p.Config.SaveName
}
case MinioStorage:
err = p.SaveToMinio()
if err != nil {
return fileInfo, err
}
fileUrl = "//" + p.Config.MinioConfig.Domain + "/" + p.Config.SavePath + p.Config.SaveName
default:
return fileInfo, errors.New("上传驱动未知")
}
fileInfo = &FileInfo{
p.File.Name,
p.File.Size,
p.File.Ext,
p.File.ContentType,
p.Config.SavePath + p.Config.SaveName,
fileUrl,
p.File.Hash,
p.File.Extra,
}
return fileInfo, err
}