Qiniu.go 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. package lib
  2. // 存储相关功能的引入包只有这两个,后面不再赘述
  3. import (
  4. "Cold_Api/conf"
  5. "context"
  6. "fmt"
  7. "io"
  8. "mime/multipart"
  9. "os"
  10. "path/filepath"
  11. "strconv"
  12. "time"
  13. "github.com/beego/beego/v2/core/logs"
  14. "github.com/qiniu/go-sdk/v7/auth/qbox"
  15. "github.com/qiniu/go-sdk/v7/storage"
  16. uuid "github.com/satori/go.uuid"
  17. )
  18. var Qiniu *qbox.Mac
  19. // var (
  20. //
  21. // //BUCKET是你在存储空间的名称
  22. // accessKey = "-8ezB_d-8-eUFTMvhOGbGzgeQRPeKQnaQ3DBcUxo"
  23. // secretKey = "KFhkYxTAJ2ZPN3ZS3euTsfWk8-C92rKgkhAMkDRN"
  24. // BUCKET = "bzdcoldoss"
  25. //
  26. // )
  27. func init() {
  28. Qiniu = qbox.NewMac(conf.Qiniu_AccessKey, conf.Qiniu_SecretKey)
  29. }
  30. // if !lib.Pload_qiniu("ofile/"+timeStr+".xlsx","ofile/"+timeStr+".xlsx"){
  31. // c.Data["json"] = lib.JSONS{Code: 202, Msg: "oss!"}
  32. // c.ServeJSON()
  33. // return
  34. // }
  35. func Pload_qiniu(localFile string, name string) bool {
  36. //localFile := "C:\\Users\\Administrator\\Downloads\\kodo-browser-Windows-x64-v1.0.15.zip"
  37. //key := "kodo-browser-Windows-x64-v1.0.15.zip"
  38. // 自定义返回值结构体
  39. type MyPutRet struct {
  40. Key string
  41. Hash string
  42. Fsize int
  43. Bucket string
  44. Name string
  45. }
  46. //key := "your file save key"
  47. // 使用 returnBody 自定义回复格式
  48. putPolicy := storage.PutPolicy{
  49. Scope: conf.Qiniu_BUCKET,
  50. ReturnBody: `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}`,
  51. }
  52. upToken := putPolicy.UploadToken(Qiniu)
  53. cfg := storage.Config{}
  54. formUploader := storage.NewFormUploader(&cfg)
  55. ret := MyPutRet{}
  56. putExtra := storage.PutExtra{
  57. Params: map[string]string{
  58. "x:name": "github logo",
  59. },
  60. }
  61. err := formUploader.PutFile(context.Background(), &ret, upToken, name, localFile, &putExtra)
  62. if err != nil {
  63. logs.Error("Pload_qiniu", err)
  64. return false
  65. }
  66. logs.Info("七牛云", ret.Bucket, ret.Key, ret.Fsize, ret.Hash, ret.Name)
  67. return true
  68. }
  69. func UploadToken(T_suffix string) string {
  70. Tokey := strconv.FormatInt(time.Now().Unix(), 10) + uuid.NewV4().String()
  71. if len(T_suffix) == 0 {
  72. T_suffix = "png"
  73. }
  74. putPolicy := storage.PutPolicy{
  75. Scope: conf.Qiniu_BUCKET,
  76. InsertOnly: 1, // 仅能以新增模式上传文件。
  77. Expires: 7200, //示例2小时有效期
  78. ReturnBody: `{"key":"` + conf.OssQiniu + `/$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)"}`,
  79. //{"key":"github-x.png","hash":"FqKXVdTvIx_mPjOYdjDyUSy_H1jr","fsize":6091,"bucket":"if-pbl","name":"github logo"}
  80. //{"key":"` + conf.Oss + `/$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)","name":"$(x:name)"}
  81. ForceSaveKey: true,
  82. SaveKey: "UpImage/" + Tokey + "." + T_suffix,
  83. FsizeLimit: 1024 * 1024 * 500, // 500M 文件大小限制,后续可注释此行不限制大小
  84. // MimeLimit: "image/*;application/pdf;application/octet-stream;application/zip;application/x-tar;application/msword;video/mp4", // 增加MP4格式支持,后续可注释此行不限制类型
  85. }
  86. upToken := putPolicy.UploadToken(Qiniu)
  87. return upToken
  88. }
  89. // UploadFileToQiniu 公共文件上传方法,上传文件到七牛云
  90. func UploadFileToQiniu(file *multipart.FileHeader, keyPrefix string) (string, error) {
  91. // 打开文件
  92. src, err := file.Open()
  93. if err != nil {
  94. return "", err
  95. }
  96. defer src.Close()
  97. // 生成唯一文件名
  98. var key string
  99. if keyPrefix == "" {
  100. key = "uploads/" + strconv.FormatInt(time.Now().Unix(), 10) + "_" + file.Filename
  101. } else {
  102. key = keyPrefix + strconv.FormatInt(time.Now().Unix(), 10) + "_" + file.Filename
  103. }
  104. // 创建临时文件
  105. tempDir := os.TempDir()
  106. tempFile := filepath.Join(tempDir, filepath.Base(key))
  107. // 确保目录存在
  108. dir := filepath.Dir(tempFile)
  109. if err := os.MkdirAll(dir, 0755); err != nil {
  110. return "", fmt.Errorf("创建临时目录失败: %v", err)
  111. }
  112. // 将上传的文件写入临时文件
  113. dst, err := os.Create(tempFile)
  114. if err != nil {
  115. return "", fmt.Errorf("创建临时文件失败: %v", err)
  116. }
  117. defer dst.Close()
  118. defer os.Remove(tempFile) // 上传后删除临时文件
  119. _, err = io.Copy(dst, src)
  120. if err != nil {
  121. return "", fmt.Errorf("写入临时文件失败: %v", err)
  122. }
  123. // 直接使用七牛云SDK上传
  124. return uploadFileDirectToQiniu(tempFile, key)
  125. }
  126. // uploadFileDirectToQiniu 直接上传文件到七牛云
  127. func uploadFileDirectToQiniu(localFile string, key string) (string, error) {
  128. // 自定义返回值结构体
  129. type QiniuUploadResult struct {
  130. Key string `json:"key"`
  131. Hash string `json:"hash"`
  132. Fsize int64 `json:"fsize"`
  133. Bucket string `json:"bucket"`
  134. }
  135. // 使用 returnBody 自定义回复格式
  136. putPolicy := storage.PutPolicy{
  137. Scope: conf.Qiniu_BUCKET,
  138. ReturnBody: `{"key":"$(key)","hash":"$(etag)","fsize":$(fsize),"bucket":"$(bucket)"}`,
  139. FsizeLimit: 1024 * 1024 * 500, // 500M 文件大小限制,后续可注释此行不限制大小
  140. // MimeLimit: "image/*;application/pdf;application/octet-stream;application/zip;application/x-tar;application/msword;video/mp4", // 增加MP4格式支持,后续可注释此行不限制类型
  141. }
  142. upToken := putPolicy.UploadToken(Qiniu)
  143. cfg := storage.Config{}
  144. formUploader := storage.NewFormUploader(&cfg)
  145. ret := QiniuUploadResult{}
  146. putExtra := storage.PutExtra{}
  147. err := formUploader.PutFile(context.Background(), &ret, upToken, key, localFile, &putExtra)
  148. if err != nil {
  149. logs.Error("UploadFileToQiniu", "上传文件失败 "+localFile, err.Error())
  150. return "", fmt.Errorf("上传文件到七牛云失败: %v", err)
  151. }
  152. logs.Info("七牛云上传成功", ret.Bucket, ret.Key, ret.Fsize, ret.Hash)
  153. return conf.Qiniu_Url + ret.Key, nil
  154. }