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.

61 lines
1.8 KiB

3 years ago
  1. package upload
  2. import (
  3. "context"
  4. "errors"
  5. "fmt"
  6. "mime/multipart"
  7. "net/http"
  8. "net/url"
  9. "time"
  10. "autocode/global"
  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. defer f.Close() // 创建文件 defer 关闭
  24. fileKey := fmt.Sprintf("%d%s", time.Now().Unix(), file.Filename)
  25. _, err := client.Object.Put(context.Background(), global.GVA_CONFIG.TencentCOS.PathPrefix+"/"+fileKey, f, nil)
  26. if err != nil {
  27. panic(err)
  28. }
  29. return global.GVA_CONFIG.TencentCOS.BaseURL + "/" + global.GVA_CONFIG.TencentCOS.PathPrefix + "/" + fileKey, fileKey, nil
  30. }
  31. // DeleteFile delete file form COS
  32. func (*TencentCOS) DeleteFile(key string) error {
  33. client := NewClient()
  34. name := global.GVA_CONFIG.TencentCOS.PathPrefix + "/" + key
  35. _, err := client.Object.Delete(context.Background(), name)
  36. if err != nil {
  37. global.GVA_LOG.Error("function bucketManager.Delete() Filed", zap.Any("err", err.Error()))
  38. return errors.New("function bucketManager.Delete() Filed, err:" + err.Error())
  39. }
  40. return nil
  41. }
  42. // NewClient init COS client
  43. func NewClient() *cos.Client {
  44. urlStr, _ := url.Parse("https://" + global.GVA_CONFIG.TencentCOS.Bucket + ".cos." + global.GVA_CONFIG.TencentCOS.Region + ".myqcloud.com")
  45. baseURL := &cos.BaseURL{BucketURL: urlStr}
  46. client := cos.NewClient(baseURL, &http.Client{
  47. Transport: &cos.AuthorizationTransport{
  48. SecretID: global.GVA_CONFIG.TencentCOS.SecretID,
  49. SecretKey: global.GVA_CONFIG.TencentCOS.SecretKey,
  50. },
  51. })
  52. return client
  53. }