oss.go 2.1 KB

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