oss.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. // Copyright 2019 getensh.com. All rights reserved.
  2. // Use of this source code is governed by getensh.com.
  3. package utils
  4. import (
  5. "adm-ods/common.in/config"
  6. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  7. )
  8. const (
  9. ossId = "LTAI4Fjs1bNMd8k8LT41Fxxn"
  10. ossSecret = "WlQJwVbxHIY4TIZwMIFA5QCye6n0Pl"
  11. ossEndpoint = "oss-cn-shanghai.aliyuncs.com"
  12. ossBucket = "gd-image"
  13. )
  14. /*
  15. func isOssConfigured() bool {
  16. if config.Conf.Oss.Endpoint == "" ||
  17. config.Conf.Oss.Bucket == "" ||
  18. config.Conf.Oss.Id == "" ||
  19. config.Conf.Oss.Secret == "" {
  20. return false
  21. }
  22. return true
  23. }
  24. // OssGetUrl 获取oss下载地址url前缀
  25. func OssGetUrl() string {
  26. if isOssConfigured() == false {
  27. return "https://" + ossBucket + "." + ossEndpoint
  28. }
  29. return "https://" + config.Conf.Oss.Bucket + "." + config.Conf.Oss.Endpoint
  30. }
  31. func ossGetInfo() (id, secret, bucket, endpoint string) {
  32. id = ossId
  33. secret = ossSecret
  34. bucket = ossBucket
  35. endpoint = ossEndpoint
  36. if isOssConfigured() {
  37. id = config.Conf.Oss.Id
  38. secret = config.Conf.Oss.Secret
  39. bucket = config.Conf.Oss.Bucket
  40. endpoint = config.Conf.Oss.Endpoint
  41. }
  42. return id, secret, bucket, endpoint
  43. }
  44. // OssUploadFile 上传文件到oss服务器
  45. func OssUploadFile(path string, fileName string) error {
  46. id, secret, buck, endpoint := ossGetInfo()
  47. client, err := oss.New(endpoint, id, secret)
  48. if err != nil {
  49. return err
  50. }
  51. // 获取存储空间。
  52. bucket, err := client.Bucket(buck)
  53. if err != nil {
  54. return err
  55. }
  56. err = bucket.PutObjectFromFile(fileName, path)
  57. return err
  58. }
  59. // OssDeleteFile 在oss服务器上删除文件
  60. func OssDeleteFile(fileName string) error {
  61. id, secret, buck, endpoint := ossGetInfo()
  62. client, err := oss.New(endpoint, id, secret)
  63. if err != nil {
  64. return err
  65. }
  66. // 获取存储空间。
  67. bucket, err := client.Bucket(buck)
  68. if err != nil {
  69. return err
  70. }
  71. err = bucket.DeleteObject(fileName)
  72. return err
  73. }*/
  74. func OssDownloadFile(objectName, downloadedFileName string) error {
  75. client, err := oss.New(config.Conf.Oss.EndPoint, config.Conf.Oss.AccessKey, config.Conf.Oss.AccessSecret)
  76. if err != nil {
  77. return err
  78. }
  79. // 获取存储空间。
  80. bucket, err := client.Bucket(config.Conf.Oss.Bucket)
  81. if err != nil {
  82. return err
  83. }
  84. // 下载文件。
  85. err = bucket.GetObjectToFile(objectName, downloadedFileName)
  86. if err != nil {
  87. return err
  88. }
  89. return nil
  90. }