oss.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. package services
  2. import (
  3. "errors"
  4. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  5. "os"
  6. "time"
  7. "eta/eta_task/utils"
  8. )
  9. /*
  10. 上传demo
  11. func init() {
  12. fmt.Println("start")
  13. randStr := utils.GetRandStringNoSpecialChar(28)
  14. fileName := randStr + ".jpg"
  15. fmt.Println("fileName:",fileName)
  16. fpath:="./1.png"
  17. resourceUrl,err:=UploadAliyun(fileName,fpath)
  18. if err!=nil {
  19. fmt.Println("UploadAliyun Err:",err.Error())
  20. return
  21. }
  22. fmt.Println("resourceUrl:",resourceUrl)
  23. fmt.Println("end")
  24. }
  25. */
  26. // 图片上传到阿里云
  27. func UploadAliyun(filename, filepath string) (string, error) {
  28. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  29. if err != nil {
  30. return "1", err
  31. }
  32. bucket, err := client.Bucket(utils.Bucketname)
  33. if err != nil {
  34. return "2", err
  35. }
  36. path := utils.UploadDir + time.Now().Format("200601/20060102/")
  37. path += filename
  38. err = bucket.PutObjectFromFile(path, filepath)
  39. if err != nil {
  40. return "3", err
  41. }
  42. path = utils.Imghost + path
  43. return path, err
  44. }
  45. // UploadAudioAliyun 音频上传到阿里云
  46. func UploadAudioAliyun(filename, filepath string) (string, error) {
  47. if utils.AccessKeyId == `` {
  48. return "0", errors.New("阿里云信息未配置")
  49. }
  50. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  51. if err != nil {
  52. return "1", err
  53. }
  54. bucket, err := client.Bucket(utils.Bucketname)
  55. if err != nil {
  56. return "2", err
  57. }
  58. path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  59. path += filename
  60. err = bucket.PutObjectFromFile(path, filepath)
  61. if err != nil {
  62. return "3", err
  63. }
  64. path = utils.Imghost + path
  65. return path, err
  66. }
  67. // 视频上传到阿里云
  68. func UploadVideoAliyun(filename, filepath, savePath string) error {
  69. defer func() {
  70. os.Remove(filepath)
  71. }()
  72. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  73. if err != nil {
  74. return err
  75. }
  76. bucket, err := client.Bucket(utils.Bucketname)
  77. if err != nil {
  78. return err
  79. }
  80. //path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  81. //path += filename
  82. err = bucket.PutObjectFromFile(savePath, filepath)
  83. if err != nil {
  84. return err
  85. }
  86. //path = utils.Imghost + path
  87. //return path,err
  88. return err
  89. }