12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- package services
- import (
- "context"
- "errors"
- "eta/eta_mini_crm_ht/utils"
- "fmt"
- "log"
- "time"
- "github.com/minio/minio-go/v7"
- "github.com/minio/minio-go/v7/pkg/credentials"
- )
- type MinioOss struct{}
- // UploadFile 上传文件
- func (m *MinioOss) UploadFile(fileName, filePath, savePath string) (string, error) {
- if utils.MinIoAccessKeyId == `` || utils.MinIoAccessKeySecret == `` {
- return "0", errors.New("MinIo信息未配置")
- }
- ctx := context.Background()
- // 此处兼容一下前后端endpoint不一致的情况, 前端用minio_endpoint后端用minio_back_endpoint, minio_back_endpoint为空则都取前者
- endpoint := utils.MinIoEndpoint
- if utils.MinIoBackEndpoint != "" {
- endpoint = utils.MinIoBackEndpoint
- }
- accessKeyID := utils.MinIoAccessKeyId
- secretAccessKey := utils.MinIoAccessKeySecret
- useSSL := false
- if utils.MinIoUseSSL == "true" {
- useSSL = true
- }
- minioClient, err := minio.New(endpoint, &minio.Options{
- Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
- Secure: useSSL,
- })
- if err != nil {
- log.Fatalln(err)
- return "1", err
- }
- bucketName := utils.MinIoBucketname
- exists, errBucketExists := minioClient.BucketExists(ctx, bucketName)
- if errBucketExists != nil || !exists {
- err = fmt.Errorf("BucketExists: %v; err: %v", exists, errBucketExists)
- return "2", err
- }
- path := savePath
- if savePath == "" {
- path = utils.MinIoUploadDir + time.Now().Format("200601/20060102/") + fileName
- }
- _, err = minioClient.FPutObject(ctx, bucketName, path, filePath, minio.PutObjectOptions{})
- if err != nil {
- log.Fatalln(err)
- return "3", err
- }
- resourceUrl := utils.MinIoPdfhost + path
- return resourceUrl, err
- }
- func (m *MinioOss) GetUploadToken() (token OssToken, err error) {
- token.AccessKeyId = utils.MinIoAccessKeyId
- token.SecretKeyId = utils.MinIoAccessKeySecret
- token.Endpoint = utils.MinIoEndpoint
- token.ImgHost = utils.MinIoPdfhost
- token.Bucketname = utils.MinIoBucketname
- token.UseSSL = utils.MinIoUseSSL
- token.RegionId = utils.MinIoRegion
- token.Port = utils.MinIoPort
- return
- }
|