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.

75 lines
2.7 KiB

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