package main
import (
"context"
"fmt"
"log"
"os"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
)
// s3文件上传
func main() {
cfg, err := config.LoadDefaultConfig(context.TODO())
if err != nil {
log.Fatalln("error:", err)
}
client := s3.NewFromConfig(cfg)
uploader := manager.NewUploader(client)
// 本地文件名称
file, err := os.Open("assets/a.jpg")
if err != nil {
log.Println("Failed opening file", "a.jpg", err)
}
defer file.Close()
// 桶名
bucket := "langlangbucket"
// s3文件路径和文件名称(桶名下面的路径)文件名字可以自定义
key := "picture/a.jpg"
result, err := uploader.Upload(context.TODO(), &s3.PutObjectInput{
Bucket: &bucket,
Key: &key,
Body: file,
})
if err != nil {
log.Fatalln("Failed to upload", "a.jpg", err)
}
log.Println("Uploaded", "a.jpg", result.Location)
// s3文件下载
downloader := manager.NewDownloader(client)
downFile := "download/a.jpg" //下载路径
fileCreate, errCreate := os.Create(downFile)
if errCreate != nil {
fmt.Println("Failed to create file", err)
return
}
defer fileCreate.Close()
downloader.Download(context.TODO(), fileCreate, &s3.GetObjectInput{
Bucket: aws.String("langlangbucket"),
Key: aws.String("picture/a.jpg"),
})
}