oss.go 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276
  1. package services
  2. import (
  3. "encoding/json"
  4. "errors"
  5. "eta/eta_mobile/services/alarm_msg"
  6. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  7. "os"
  8. "time"
  9. "eta/eta_mobile/utils"
  10. "github.com/aliyun/alibaba-cloud-sdk-go/services/sts"
  11. )
  12. /*
  13. 上传demo
  14. func init() {
  15. fmt.Println("start")
  16. randStr := utils.GetRandStringNoSpecialChar(28)
  17. fileName := randStr + ".jpg"
  18. fmt.Println("fileName:",fileName)
  19. fpath:="./1.png"
  20. resourceUrl,err:=UploadAliyun(fileName,fpath)
  21. if err!=nil {
  22. fmt.Println("UploadAliyun Err:",err.Error())
  23. return
  24. }
  25. fmt.Println("resourceUrl:",resourceUrl)
  26. fmt.Println("end")
  27. }
  28. */
  29. // 图片上传到阿里云
  30. func UploadAliyun(filename, filepath string) (string, error) {
  31. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  32. if err != nil {
  33. return "1", err
  34. }
  35. bucket, err := client.Bucket(utils.Bucketname)
  36. if err != nil {
  37. return "2", err
  38. }
  39. path := utils.UploadDir + time.Now().Format("200601/20060102/")
  40. path += filename
  41. err = bucket.PutObjectFromFile(path, filepath)
  42. if err != nil {
  43. return "3", err
  44. }
  45. path = utils.Imghost + path
  46. return path, err
  47. }
  48. // UploadAliyunV2 图片上传到阿里云
  49. func UploadAliyunV2(filename, filepath string) (string, error) {
  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.UploadDir + 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 UploadAudioAliyun(filename, filepath string) (string, error) {
  69. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  70. if err != nil {
  71. return "1", err
  72. }
  73. bucket, err := client.Bucket(utils.Bucketname)
  74. if err != nil {
  75. return "2", err
  76. }
  77. path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  78. path += filename
  79. err = bucket.PutObjectFromFile(path, filepath)
  80. if err != nil {
  81. return "3", err
  82. }
  83. path = utils.Imghost + path
  84. return path, err
  85. }
  86. // 视频上传到阿里云
  87. func UploadVideoAliyun(filename, filepath, savePath string) error {
  88. defer func() {
  89. os.Remove(filepath)
  90. }()
  91. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  92. if err != nil {
  93. return err
  94. }
  95. bucket, err := client.Bucket(utils.Bucketname)
  96. if err != nil {
  97. return err
  98. }
  99. //path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  100. //path += filename
  101. err = bucket.PutObjectFromFile(savePath, filepath)
  102. if err != nil {
  103. return err
  104. }
  105. //path = utils.Imghost + path
  106. //return path,err
  107. return err
  108. }
  109. const (
  110. HzEndpoint = "oss-cn-shanghai.aliyuncs.com"
  111. HzBucketName string = "hzchart"
  112. )
  113. // 上传文件到阿里云
  114. func UploadFileToAliyun(filename, filepath, savePath string) error {
  115. defer func() {
  116. os.Remove(filepath)
  117. }()
  118. client, err := oss.New(HzEndpoint, utils.AccessKeyId, utils.AccessKeySecret)
  119. if err != nil {
  120. return err
  121. }
  122. bucket, err := client.Bucket(HzBucketName)
  123. if err != nil {
  124. return err
  125. }
  126. //path := utils.Upload_Audio_Dir + time.Now().Format("200601/20060102/")
  127. //path += filename
  128. err = bucket.PutObjectFromFile(savePath, filepath)
  129. if err != nil {
  130. return err
  131. }
  132. //path = utils.Imghost + path
  133. //return path,err
  134. return err
  135. }
  136. type STSToken struct {
  137. AccessKeyId string
  138. AccessKeySecret string
  139. SecurityToken string
  140. ExpiredTime string
  141. RegionId string
  142. Bucketname string
  143. Endpoint string
  144. Imghost string
  145. }
  146. // GetOssSTSToken 获取STSToken
  147. func GetOssSTSToken() (item *STSToken, err error) {
  148. defer func() {
  149. if err != nil {
  150. utils.FileLog.Info(err.Error())
  151. go alarm_msg.SendAlarmMsg("获取STSToken失败, ErrMsg: "+err.Error(), 3)
  152. }
  153. }()
  154. item = new(STSToken)
  155. // 获取缓存中的Token
  156. recent, _ := utils.Rc.RedisString(utils.STSTokenCacheKey)
  157. if recent != "" {
  158. lastToken := new(STSToken)
  159. if e := json.Unmarshal([]byte(recent), &lastToken); e != nil {
  160. err = errors.New("GetOssSTSToken lastToken Unmarshal Err: " + e.Error())
  161. return
  162. }
  163. // 未防止正在上传大文件时Token过期, 将判定的过期时间提前10分钟
  164. afterTime := time.Now().Local().Add(10 * time.Minute)
  165. expired, e := time.ParseInLocation(utils.FormatDateTime, lastToken.ExpiredTime, time.Local)
  166. if e != nil {
  167. err = errors.New("GetOssSTSToken expiredTime Parse Err: " + e.Error())
  168. return
  169. }
  170. if expired.After(afterTime) {
  171. item.AccessKeyId = lastToken.AccessKeyId
  172. item.AccessKeySecret = lastToken.AccessKeySecret
  173. item.SecurityToken = lastToken.SecurityToken
  174. item.ExpiredTime = lastToken.ExpiredTime
  175. return
  176. }
  177. }
  178. // 已过期则获取新的token
  179. newToken, e := NewSTSToken()
  180. if e != nil {
  181. err = errors.New("GetOssSTSToken NewSTSToken Err: " + e.Error())
  182. return
  183. }
  184. newTokenJson, e := json.Marshal(newToken)
  185. if e != nil {
  186. err = errors.New("GetOssSTSToken NewToken JSON Err: " + e.Error())
  187. return
  188. }
  189. // 覆盖缓存
  190. if e := utils.Rc.Put(utils.STSTokenCacheKey, newTokenJson, time.Hour); e != nil {
  191. err = errors.New("GetOssSTSToken SetRedis Err: " + e.Error())
  192. return
  193. }
  194. item = newToken
  195. return
  196. }
  197. // NewSTSToken 获取一个新的STSToken
  198. func NewSTSToken() (item *STSToken, err error) {
  199. defer func() {
  200. if err != nil {
  201. utils.FileLog.Info(err.Error())
  202. }
  203. }()
  204. item = new(STSToken)
  205. client, e := sts.NewClientWithAccessKey("cn-shanghai", utils.RAMAccessKeyId, utils.RAMAccessKeySecret)
  206. if e != nil {
  207. err = errors.New("NewSTSToken NewClient Err: " + e.Error())
  208. return
  209. }
  210. request := sts.CreateAssumeRoleRequest()
  211. request.Scheme = utils.AliStsScheme
  212. request.RegionId = utils.RegionId
  213. request.RoleArn = utils.RoleArn
  214. now := time.Now().Format(utils.FormatDateTimeUnSpace)
  215. request.RoleSessionName = utils.RoleSessionName + now
  216. request.DurationSeconds = "3600"
  217. request.ConnectTimeout = 300 * time.Second
  218. request.ReadTimeout = 300 * time.Second
  219. response, e := client.AssumeRole(request)
  220. if e != nil {
  221. err = errors.New("NewSTSToken AssumeRole Err: " + e.Error())
  222. return
  223. }
  224. if response != nil {
  225. item.AccessKeyId = response.Credentials.AccessKeyId
  226. item.AccessKeySecret = response.Credentials.AccessKeySecret
  227. item.SecurityToken = response.Credentials.SecurityToken
  228. t, _ := time.Parse(time.RFC3339, response.Credentials.Expiration)
  229. expiration := t.In(time.Local)
  230. item.ExpiredTime = expiration.Format(utils.FormatDateTime)
  231. item.RegionId = utils.RegionId
  232. item.Bucketname = utils.Bucketname
  233. item.Endpoint = utils.Imghost
  234. item.Imghost = utils.Imghost
  235. }
  236. return
  237. }
  238. // UploadAliyunToDir 上传至hzchart
  239. func UploadAliyunToDir(filename, filepath, uploadDir, fileDir string) (string, error) {
  240. client, err := oss.New(utils.Endpoint, utils.AccessKeyId, utils.AccessKeySecret)
  241. if err != nil {
  242. return "1", err
  243. }
  244. bucket, err := client.Bucket(utils.Bucketname)
  245. if err != nil {
  246. return "2", err
  247. }
  248. if uploadDir == "" {
  249. uploadDir = utils.UploadDir
  250. }
  251. if fileDir == "" {
  252. fileDir = time.Now().Format("200601/20060102/")
  253. }
  254. path := uploadDir + fileDir
  255. path += filename
  256. err = bucket.PutObjectFromFile(path, filepath)
  257. if err != nil {
  258. return "3", err
  259. }
  260. path = utils.Imghost + path
  261. return path, err
  262. }