You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.5 KiB

  1. package upload
  2. import (
  3. "errors"
  4. "gin-vue-admin/global"
  5. "github.com/aliyun/aliyun-oss-go-sdk/oss"
  6. "go.uber.org/zap"
  7. "mime/multipart"
  8. "path/filepath"
  9. "time"
  10. )
  11. type AliyunOSS struct{}
  12. func (*AliyunOSS) UploadFile(file *multipart.FileHeader) (string, string, error) {
  13. bucket, err := NewBucket()
  14. if err != nil {
  15. global.GVA_LOG.Error("function AliyunOSS.NewBucket() Failed", zap.Any("err", err.Error()))
  16. return "", "", errors.New("function AliyunOSS.NewBucket() Failed, err:" + err.Error())
  17. }
  18. // 读取本地文件。
  19. f, openError := file.Open()
  20. if openError != nil {
  21. global.GVA_LOG.Error("function file.Open() Failed", zap.Any("err", openError.Error()))
  22. return "", "", errors.New("function file.Open() Failed, err:" + openError.Error())
  23. }
  24. //上传阿里云路径 文件名格式 自己可以改 建议保证唯一性
  25. yunFileTmpPath := filepath.Join("uploads", time.Now().Format("2006-01-02")) + "/" + file.Filename
  26. // 上传文件流。
  27. err = bucket.PutObject(yunFileTmpPath, f)
  28. if err != nil {
  29. global.GVA_LOG.Error("function formUploader.Put() Failed", zap.Any("err", err.Error()))
  30. return "", "", errors.New("function formUploader.Put() Failed, err:" + err.Error())
  31. }
  32. return global.GVA_CONFIG.AliyunOSS.BucketUrl + "/" + yunFileTmpPath, yunFileTmpPath, nil
  33. }
  34. func (*AliyunOSS) DeleteFile(key string) error {
  35. bucket, err := NewBucket()
  36. if err != nil {
  37. global.GVA_LOG.Error("function AliyunOSS.NewBucket() Failed", zap.Any("err", err.Error()))
  38. return errors.New("function AliyunOSS.NewBucket() Failed, err:" + err.Error())
  39. }
  40. // 删除单个文件。objectName表示删除OSS文件时需要指定包含文件后缀在内的完整路径,例如abc/efg/123.jpg。
  41. // 如需删除文件夹,请将objectName设置为对应的文件夹名称。如果文件夹非空,则需要将文件夹下的所有object删除后才能删除该文件夹。
  42. err = bucket.DeleteObject(key)
  43. if err != nil {
  44. global.GVA_LOG.Error("function bucketManager.Delete() Filed", zap.Any("err", err.Error()))
  45. return errors.New("function bucketManager.Delete() Filed, err:" + err.Error())
  46. }
  47. return nil
  48. }
  49. func NewBucket() (*oss.Bucket, error) {
  50. // 创建OSSClient实例。
  51. client, err := oss.New(global.GVA_CONFIG.AliyunOSS.Endpoint, global.GVA_CONFIG.AliyunOSS.AccessKeyId, global.GVA_CONFIG.AliyunOSS.AccessKeySecret)
  52. if err != nil {
  53. return nil, err
  54. }
  55. // 获取存储空间。
  56. bucket, err := client.Bucket(global.GVA_CONFIG.AliyunOSS.BucketName)
  57. if err != nil {
  58. return nil, err
  59. }
  60. return bucket, nil
  61. }