minio.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. package services
  2. import (
  3. "context"
  4. "errors"
  5. "eta/eta_mini_crm/utils"
  6. "fmt"
  7. "log"
  8. "time"
  9. "github.com/minio/minio-go/v7"
  10. "github.com/minio/minio-go/v7/pkg/credentials"
  11. )
  12. type MinioOss struct{}
  13. // UploadFile 上传文件
  14. func (m *MinioOss) UploadFile(fileName, filePath, savePath string) (string, error) {
  15. if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
  16. return "0", errors.New("MinIo信息未配置")
  17. }
  18. ctx := context.Background()
  19. // 此处兼容一下前后端endpoint不一致的情况, 前端用minio_endpoint后端用minio_back_endpoint, minio_back_endpoint为空则都取前者
  20. endpoint := utils.MinIoEndpoint
  21. if utils.MinIoBackEndpoint != "" {
  22. endpoint = utils.MinIoBackEndpoint
  23. }
  24. accessKeyID := utils.MinIoAccessKeyId
  25. secretAccessKey := utils.MinIoAccessKeySecret
  26. useSSL := false
  27. if utils.MinIoUseSSL == "true" {
  28. useSSL = true
  29. }
  30. minioClient, err := minio.New(endpoint, &minio.Options{
  31. Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
  32. Secure: useSSL,
  33. })
  34. if err != nil {
  35. log.Fatalln(err)
  36. return "1", err
  37. }
  38. bucketName := utils.MinIoBucketname
  39. exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
  40. if errBucketExists != nil || !exists {
  41. err = fmt.Errorf("BucketExists: %v; err: %v", exists, errBucketExists)
  42. return "2", err
  43. }
  44. path := savePath
  45. if savePath == "" {
  46. path = utils.MinIoUploadDir + time.Now().Format("200601/20060102/") + fileName
  47. }
  48. _, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
  49. if err != nil {
  50. log.Fatalln(err)
  51. return "3", err
  52. }
  53. resourceUrl := utils.MinIoPdfhost + path
  54. return resourceUrl, err
  55. }
  56. func (m *MinioOss) GetUploadToken() (token OssToken, err error) {
  57. token.AccessKeyId = utils.MinIoAccessKeyId
  58. token.SecretKeyId = utils.MinIoAccessKeySecret
  59. token.Endpoint = utils.MinIoEndpoint
  60. token.ImgHost = utils.MinIoPdfhost
  61. token.Bucketname = utils.MinIoBucketname
  62. token.UseSSL = utils.MinIoUseSSL
  63. token.RegionId = utils.MinIoRegion
  64. token.Port = utils.MinIoPort
  65. return
  66. }