-
Notifications
You must be signed in to change notification settings - Fork 0
/
resolver-src-upload.go
executable file
·75 lines (63 loc) · 1.79 KB
/
resolver-src-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
package templates
var UpLoad = `package src
import(
"fmt"
"io"
"os"
"path"
"time"
"context"
"strings"
"net/http"
"github.com/gofrs/uuid"
"{{.Config.Package}}/gen"
"{{.Config.Package}}/utils"
)
func (r *MutationResolver) Upload(ctx context.Context, files []*gen.FileField) (resData interface{}, err error) {
if len(files) <= 0 {
return nil, fmt.Errorf("上传文件不能为空")
}
tx := gen.GetTransaction(ctx)
unix := time.Unix(time.Now().Unix(), 0)
fileDate := unix.Format("2006-01")
err = os.MkdirAll("./uploads/" + fileDate, os.ModePerm)
if err != nil {
return resData, err
}
var forError error = nil
uploadImage := []string{}
for _, v := range files {
hash := v.Hash
if hash == "" {
hash = utils.EncryptMd5(uuid.Must(uuid.NewV4()).String())
}
uploadFile := gen.UploadFile{}
if err := tx.Select("id, name").Where("hash = ?", hash).First(&uploadFile).Error; err == nil {
uploadImage = append(uploadImage, uploadFile.Name)
} else {
file := v.File
filesuffix := strings.ToLower(path.Ext(file.Filename)) // 文件后缀名
filePath := "./uploads/" + fileDate + "/" + uuid.Must(uuid.NewV4()).String() + filesuffix
// filePath := "./uploads/" + fileDate + "/" + v.Filename
saveFile, err := os.OpenFile(filePath, os.O_WRONLY|os.O_CREATE, 0666)
defer saveFile.Close()
if err == nil {
uploadFile.ID = uuid.Must(uuid.NewV4()).String()
uploadFile.Name = filePath
uploadFile.Hash = hash
tx.Create(&uploadFile)
uploadImage = append(uploadImage, filePath)
io.Copy(saveFile, file.File);
} else {
forError = err
break
}
}
}
if forError != nil {
return resData, forError
}
resData = uploadImage
return resData, err
}
`