任务一完成
This commit is contained in:
@@ -0,0 +1,84 @@
|
||||
package upload
|
||||
|
||||
import (
|
||||
"context"
|
||||
"mime/multipart"
|
||||
"path"
|
||||
|
||||
"github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
)
|
||||
|
||||
// Minio MinIO存储
|
||||
type Minio struct {
|
||||
ID string
|
||||
Secret string
|
||||
Bucket string
|
||||
Endpoint string
|
||||
BasePath string
|
||||
UseSSL bool
|
||||
}
|
||||
|
||||
// NewMinio 创建MinIO
|
||||
func NewMinio(id, secret, bucket, endpoint, basePath string, useSSL bool) *Minio {
|
||||
return &Minio{
|
||||
ID: id,
|
||||
Secret: secret,
|
||||
Bucket: bucket,
|
||||
Endpoint: endpoint,
|
||||
BasePath: basePath,
|
||||
UseSSL: useSSL,
|
||||
}
|
||||
}
|
||||
|
||||
func (m *Minio) getClient() (*minio.Client, error) {
|
||||
return minio.New(m.Endpoint, &minio.Options{
|
||||
Creds: credentials.NewStaticV4(m.ID, m.Secret, ""),
|
||||
Secure: m.UseSSL,
|
||||
})
|
||||
}
|
||||
|
||||
// Upload 上传文件
|
||||
func (m *Minio) Upload(file *multipart.FileHeader) (string, string, error) {
|
||||
client, err := m.getClient()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
// 生成文件名和路径
|
||||
fileName := GenerateFileName(file.Filename)
|
||||
filePath := GeneratePath(m.BasePath)
|
||||
key := path.Join(filePath, fileName)
|
||||
|
||||
// 打开文件
|
||||
src, err := file.Open()
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
defer src.Close()
|
||||
|
||||
// 上传
|
||||
_, err = client.PutObject(context.Background(), m.Bucket, key, src, file.Size, minio.PutObjectOptions{
|
||||
ContentType: file.Header.Get("Content-Type"),
|
||||
})
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
// 返回访问URL和key
|
||||
protocol := "http"
|
||||
if m.UseSSL {
|
||||
protocol = "https"
|
||||
}
|
||||
accessURL := protocol + "://" + m.Endpoint + "/" + m.Bucket + "/" + key
|
||||
return accessURL, key, nil
|
||||
}
|
||||
|
||||
// Delete 删除文件
|
||||
func (m *Minio) Delete(key string) error {
|
||||
client, err := m.getClient()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return client.RemoveObject(context.Background(), m.Bucket, key, minio.RemoveObjectOptions{})
|
||||
}
|
||||
Reference in New Issue
Block a user