oss.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package services
  2. import (
  3. "errors"
  4. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  5. "os"
  6. "time"
  7. "eta/eta_report/utils"
  8. )
  9. // UploadAliyunToDir 上传至hzchart
  10. //func UploadAliyunToDir(filename, filepath, uploadDir, fileDir string) (string, error) {
  11. // if utils.AccessKeyId == `` {
  12. // return "0", errors.New("阿里云信息未配置")
  13. // }
  14. // client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  15. // if err != nil {
  16. // return "1", err
  17. // }
  18. // bucket, err := client.Bucket(utils.Bucketname)
  19. // if err != nil {
  20. // return "2", err
  21. // }
  22. // if uploadDir == "" {
  23. // uploadDir = utils.UploadDir
  24. // }
  25. // if fileDir == "" {
  26. // fileDir = time.Now().Format("200601/20060102/")
  27. // }
  28. // path := uploadDir + fileDir
  29. // path += filename
  30. // err = bucket.PutObjectFromFile(path, filepath)
  31. // if err != nil {
  32. // return "3", err
  33. // }
  34. // path = utils.Imghost + path
  35. // return path, err
  36. //}
  37. type AliOss struct{}
  38. // UploadFile 上传文件
  39. func (m *AliOss) UploadFile(fileName, filePath, savePath string) (string, error) {
  40. defer func() {
  41. _ = os.Remove(filePath)
  42. }()
  43. if utils.AccessKeyId == `` {
  44. return "0", errors.New("阿里云信息未配置")
  45. }
  46. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  47. if err != nil {
  48. return "1", err
  49. }
  50. bucket, err := client.Bucket(utils.Bucketname)
  51. if err != nil {
  52. return "2", err
  53. }
  54. path := savePath
  55. if savePath == "" {
  56. path = utils.UploadDir + time.Now().Format("200601/20060102/") + fileName
  57. }
  58. err = bucket.PutObjectFromFile(path, filePath)
  59. if err != nil {
  60. return "3", err
  61. }
  62. resourceUrl := utils.Imghost + path
  63. return resourceUrl, err
  64. }
  65. func (m *AliOss) GetUploadToken() (token OssToken, err error) {
  66. //stsToken, e := GetOssSTSToken()
  67. //if e != nil {
  68. // err = fmt.Errorf("GetOssSTSToken err: %s", e.Error())
  69. // return
  70. //}
  71. //token.AccessKeyId = stsToken.AccessKeyId
  72. //token.AccessKeySecret = stsToken.AccessKeySecret
  73. //token.SecurityToken = stsToken.SecurityToken
  74. //token.ExpiredTime = stsToken.ExpiredTime
  75. //token.RegionId = stsToken.RegionId
  76. //token.Bucketname = stsToken.Bucketname
  77. //token.Endpoint = stsToken.Endpoint
  78. //token.Imghost = stsToken.Imghost
  79. return
  80. }