package main
import (
"context"
"fmt"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
"io"
"log"
"mime"
"os"
"path/filepath"
)
// 在MinIO中,文件和对象是等效的概念。每个文件都是一个对象(文件夹),
// 并由一个唯一的对象名称标识。因此,在MinIO中,删除文件和删除对象是相同的操作
func main() {
endpoint := "192.168.252.128:9000" // Minio服务器的endpoint
accessKeyID := "admin" // Minio服务器的Access Key
secretAccessKey := "admin123456" // Minio服务器的Secret Key
// 初始化Minio客戶端
minioClient, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKeyID, secretAccessKey, ""),
Secure: false,
})
if err != nil {
log.Fatalln("000", err)
}
// 设定上传件的bucket和object名称,以及本地文件路径
bucketName := "test"
objectName := "images"
filePath := "Z:\\hook\\output.xlsx"
if exists, err := minioClient.BucketExists(context.Background(), bucketName); !exists {
err = minioClient.MakeBucket(context.Background(), bucketName, minio.MakeBucketOptions{Region: "us-east-1"})
if err != nil {
log.Fatalln("001", err)
}
}
// 打开本地文件并获取文件信息
fileType := mime.TypeByExtension(filepath.Ext(filePath))
fmt.Println(fileType)
//上传文件
uploadObject(minioClient, bucketName, objectName, filePath, fileType)
//下载文件
//downObject(minioClient, bucketName, objectName, filePath)
//删除文件
//removeObject(minioClient, bucketName, objectName)
}
// 上传对象
func uploadObject(minioClient *minio.Client, bulkName, objectName, localFileName, fileType string) {
_, err := minioClient.FPutObject(context.Background(), bulkName, objectName, localFileName, minio.PutObjectOptions{
ContentType: fileType,
})
if err != nil {
log.Fatalf("upload object error " + err.Error())
}
}
// 下载对象
func downObject(minioClient *minio.Client, bulkName, objectName, localFileName string) {
object, err := minioClient.GetObject(context.Background(), bulkName, objectName, minio.GetObjectOptions{})
if err != nil {
log.Fatalf("download object error " + err.Error())
return
}
localFile, err := os.Create(localFileName)
if err != nil {
log.Fatalf("create local object error " + err.Error())
}
_, err = io.Copy(localFile, object)
if err != nil {
log.Fatalf("write object from object to local file error " + err.Error())
return
}
}
// 删除对象
func removeObject(minioClient *minio.Client, bulkName, objectName string) {
err := minioClient.RemoveObject(context.Background(), bulkName, objectName, minio.RemoveObjectOptions{})
if err != nil {
log.Fatalf("remove object eror " + err.Error())
return
}
}