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.

59 lines
1.8 KiB

  1. package upload
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "gin-vue-admin/global"
  7. "mime/multipart"
  8. "net/http"
  9. "net/url"
  10. "time"
  11. "github.com/tencentyun/cos-go-sdk-v5"
  12. "go.uber.org/zap"
  13. )
  14. type TencentCOS struct{}
  15. // UploadFile upload file to COS
  16. func (*TencentCOS) UploadFile(file *multipart.FileHeader) (string, string, error) {
  17. client := NewClient()
  18. f, openError := file.Open()
  19. if openError != nil {
  20. global.GVA_LOG.Error("function file.Open() Filed", zap.Any("err", openError.Error()))
  21. return "", "", errors.New("function file.Open() Filed, err:" + openError.Error())
  22. }
  23. fileKey := fmt.Sprintf("%d%s", time.Now().Unix(), file.Filename)
  24. _, err := client.Object.Put(context.Background(), global.GVA_CONFIG.TencentCOS.PathPrefix+"/"+fileKey, f, nil)
  25. if err != nil {
  26. panic(err)
  27. }
  28. return global.GVA_CONFIG.TencentCOS.BaseURL + "/" + global.GVA_CONFIG.TencentCOS.PathPrefix + "/" + fileKey, fileKey, nil
  29. }
  30. // DeleteFile delete file form COS
  31. func (*TencentCOS) DeleteFile(key string) error {
  32. client := NewClient()
  33. name := global.GVA_CONFIG.TencentCOS.PathPrefix + "/" + key
  34. _, err := client.Object.Delete(context.Background(), name)
  35. if err != nil {
  36. global.GVA_LOG.Error("function bucketManager.Delete() Filed", zap.Any("err", err.Error()))
  37. return errors.New("function bucketManager.Delete() Filed, err:" + err.Error())
  38. }
  39. return nil
  40. }
  41. // NewClient init COS client
  42. func NewClient() *cos.Client {
  43. urlStr, _ := url.Parse("https://" + global.GVA_CONFIG.TencentCOS.Bucket + ".cos." + global.GVA_CONFIG.TencentCOS.Region + ".myqcloud.com")
  44. baseURL := &cos.BaseURL{BucketURL: urlStr}
  45. client := cos.NewClient(baseURL, &http.Client{
  46. Transport: &cos.AuthorizationTransport{
  47. SecretID: global.GVA_CONFIG.TencentCOS.SecretID,
  48. SecretKey: global.GVA_CONFIG.TencentCOS.SecretKey,
  49. },
  50. })
  51. return client
  52. }