You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.5 KiB

  1. package upload
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "gin-vue-admin/global"
  7. "github.com/qiniu/api.v7/v7/auth/qbox"
  8. "github.com/qiniu/api.v7/v7/storage"
  9. "go.uber.org/zap"
  10. "mime/multipart"
  11. "time"
  12. )
  13. type Qiniu struct{}
  14. // Upload 上传文件
  15. func (*Qiniu) UploadFile(file *multipart.FileHeader) (string, string, error) {
  16. putPolicy := storage.PutPolicy{Scope: global.GVA_CONFIG.Qiniu.Bucket}
  17. mac := qbox.NewMac(global.GVA_CONFIG.Qiniu.AccessKey, global.GVA_CONFIG.Qiniu.SecretKey)
  18. upToken := putPolicy.UploadToken(mac)
  19. cfg := qiniuConfig()
  20. formUploader := storage.NewFormUploader(cfg)
  21. ret := storage.PutRet{}
  22. putExtra := storage.PutExtra{Params: map[string]string{"x:name": "github logo"}}
  23. f, openError := file.Open()
  24. if openError != nil {
  25. global.GVA_LOG.Error("function file.Open() Filed", zap.Any("err", openError.Error()))
  26. return "", "", errors.New("function file.Open() Filed, err:" + openError.Error())
  27. }
  28. fileKey := fmt.Sprintf("%d%s", time.Now().Unix(), file.Filename) // 文件名格式 自己可以改 建议保证唯一性
  29. putErr := formUploader.Put(context.Background(), &ret, upToken, fileKey, f, file.Size, &putExtra)
  30. if putErr != nil {
  31. global.GVA_LOG.Error("function formUploader.Put() Filed", zap.Any("err", putErr.Error()))
  32. return "", "", errors.New("function formUploader.Put() Filed, err:" + putErr.Error())
  33. }
  34. return global.GVA_CONFIG.Qiniu.ImgPath + "/" + ret.Key, ret.Key, nil
  35. }
  36. // DeleteFile 删除文件
  37. func (*Qiniu) DeleteFile(key string) error {
  38. mac := qbox.NewMac(global.GVA_CONFIG.Qiniu.AccessKey, global.GVA_CONFIG.Qiniu.SecretKey)
  39. cfg := qiniuConfig()
  40. bucketManager := storage.NewBucketManager(mac, cfg)
  41. if err := bucketManager.Delete(global.GVA_CONFIG.Qiniu.Bucket, key); err != nil{
  42. global.GVA_LOG.Error("function bucketManager.Delete() Filed", zap.Any("err", err.Error()))
  43. return errors.New("function bucketManager.Delete() Filed, err:" + err.Error())
  44. }
  45. return nil
  46. }
  47. // config 根据配置文件进行返回七牛云的配置
  48. func qiniuConfig() *storage.Config {
  49. cfg := storage.Config{
  50. UseHTTPS: global.GVA_CONFIG.Qiniu.UseHTTPS,
  51. UseCdnDomains: global.GVA_CONFIG.Qiniu.UseCdnDomains,
  52. }
  53. switch global.GVA_CONFIG.Qiniu.Zone { // 根据配置文件进行初始化空间对应的机房
  54. case "ZoneHuadong":
  55. cfg.Zone = &storage.ZoneHuadong
  56. case "ZoneHuabei":
  57. cfg.Zone = &storage.ZoneHuabei
  58. case "ZoneHuanan":
  59. cfg.Zone = &storage.ZoneHuanan
  60. case "ZoneBeimei":
  61. cfg.Zone = &storage.ZoneBeimei
  62. case "ZoneXinjiapo":
  63. cfg.Zone = &storage.ZoneXinjiapo
  64. }
  65. return &cfg
  66. }