Golang 上传远程图片到 MinIO 存储
以下是使用 Golang 将远程 URL 图片文件上传到 MinIO 的示例代码:
package main
import (
"context"
"fmt"
"io"
"net/http"
"os"
"github.com/minio/minio-go/v7"
"github.com/minio/minio-go/v7/pkg/credentials"
)
func main() {
// 连接到minio服务器
endpoint := "minio.example.com:9000"
accessKey := "ACCESS_KEY"
secretKey := "SECRET_KEY"
useSSL := false
bucketName := "mybucket"
// 初始化minio client
minioClient, err := minio.New(endpoint, &minio.Options{
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
Secure: useSSL,
})
if err != nil {
fmt.Println(err)
return
}
// 获取远程图片文件
imageUrl := "https://example.com/image.jpg"
response, err := http.Get(imageUrl)
if err != nil {
fmt.Println(err)
return
}
defer response.Body.Close()
// 上传图片文件到minio
objectName := "image.jpg"
contentType := "image/jpeg"
_, err = minioClient.PutObject(context.Background(), bucketName, objectName, response.Body, -1, minio.PutObjectOptions{
ContentType: contentType,
})
if err != nil {
fmt.Println(err)
return
}
// 打印上传成功的消息
fmt.Printf("Successfully uploaded %s\n", objectName)
}
需要注意的是,此代码示例使用 minio-go v7 版本的 minio 客户端库,如果您使用的是旧版本的 minio-go 库,请相应地进行修改。
原文地址: https://www.cveoy.top/t/topic/lHT1 著作权归作者所有。请勿转载和采集!