-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.go
102 lines (91 loc) · 2.64 KB
/
main.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
package main
import (
"mime/multipart"
"net/http"
"path/filepath"
"pichub/middleware"
"pichub/utils"
"strconv"
"time"
"context"
"net/url"
"github.com/gin-gonic/gin"
cos "github.com/tencentyun/cos-go-sdk-v5"
)
func main() {
router := gin.Default()
router.Static("/i", "./upload")
router.Static("/static", "./web")
router.Use(middleware.Cors())
router.GET("/", func(c *gin.Context) {
// 将index.html作为响应发送
c.File("./web/index.html")
})
router.MaxMultipartMemory = 8 << 20 // 8 MiB
router.POST("/upload", func(c *gin.Context) {
file, _ := c.FormFile("file")
code := 415
msg := "抱歉,您上传的数据,格式不支持!"
contentType := file.Header.Get("Content-Type")
if contentType != "" && len(contentType) > 6 && contentType[:6] == "image/" {
switch {
case utils.PICK_SERVICE == "local":
msg = localUpload(utils.LOCAL_BASE_FOLDER, file, c)
case utils.PICK_SERVICE == "tencent":
msg = cosUpload(file.Filename, file)
}
code = 200
}
c.JSON(http.StatusOK, gin.H{
"status": code,
"msg": msg,
})
})
router.Run(utils.SERVER_PORT)
}
// 获取URL
func getHost(request *http.Request) string {
scheme := "http"
if request.TLS != nil {
scheme = "https"
}
host := request.Host
return scheme + "://" + host
}
// 根据上传日期创建保存路径,文件名为时间戳
func createFilePath(filename string) string {
now := time.Now()
year := now.Format("2006")
month := now.Format("01")
day := now.Format("02")
timestamp := now.Unix()
datePath := year + "/" + month + "/" + day + "/"
return datePath + strconv.Itoa(int(timestamp)) + filepath.Ext(filename)
}
// 腾讯COS对象存储上传方法
func cosUpload(filename string, file *multipart.FileHeader) string {
u, _ := url.Parse(utils.TENCENT_COS_URL)
b := &cos.BaseURL{BucketURL: u}
c := cos.NewClient(b, &http.Client{
Transport: &cos.AuthorizationTransport{
SecretID: utils.TENCENT_COS_SECRETID,
SecretKey: utils.TENCENT_COS_SECRETKEY,
},
})
name := "pichub/" + createFilePath(filename)
src, _ := file.Open()
defer src.Close()
_, err := c.Object.Put(context.Background(), name, src, nil)
if err != nil {
panic(err)
}
return utils.TENCENT_COS_URL + "/" + name
}
// 本地上传方法
func localUpload(basePath string, file *multipart.FileHeader, c *gin.Context) string { // 指定basePath基础的文件夹路径
fullURL := getHost(c.Request)
filePath := createFilePath(file.Filename) // 2024/08/16/1723794210.png
uploadPath := basePath + filePath // ./upload/2024/08/16/1723794210.png
c.SaveUploadedFile(file, uploadPath) // 上传文件至指定的完整文件路径
return fullURL + "/i/" + filePath
}