oss.go 7.3 KB

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