v2
官方推荐版本,需要go版本>=1.20
安装
bash
go get github.com/aws/aws-sdk-go-v2
go get github.com/aws/aws-sdk-go-v2/config
go get github.com/aws/aws-sdk-go-v2/service/s3
必要参数
bucket
: 存储桶的名称
Region
: 存储桶所在区域,例us-east-1
accessKeyID
: 访问存储桶所需的KeyID
secretAccessKey
: 访问存储桶所需的AccessKey
如何获取accessKeyID
和secretAccessKey
:指南
go
var (
s3Client *s3.Client
bucket = "yourbucketname"
)
func InitS3Client() {
accessKeyID := "xxxxx"
secretAccessKey := "xxxxx"
cfg, err := config.LoadDefaultConfig(context.TODO(),
config.WithRegion("us-east-1"),
config.WithCredentialsProvider(credentials.NewStaticCredentialsProvider(accessKeyID, secretAccessKey, "")),
)
if err != nil {
log.Fatalf("unable to load SDK config, %v", err)
}
s3Client = s3.NewFromConfig(cfg)
}
func UploadToS3(filePath, fileName, mimeType string) (string, error) {
file, err := os.Open(filePath)
if err != nil {
return "", fmt.Errorf("failed to open file %q, %v", filePath, err)
}
defer file.Close()
_, err = s3Client.PutObject(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(fileName),
Body: file,
ContentType: aws.String(mimeType),
})
if err != nil {
return "", fmt.Errorf("failed to upload file to S3, %v", err)
}
return fmt.Sprintf("https://%s.s3.amazonaws.com/%s", bucket, fileName), nil
}
若不想升级go1.20,可以使用v1版本
v1
安装
bash
go get github.com/aws/aws-sdk-go
go
var (
s3Client *s3.S3
bucket = "yourbucketname"
)
func InitS3Client() {
accessKeyID := "xxxxx"
secretAccessKey := "xxxxx"
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-east-1"),
Credentials: credentials.NewStaticCredentials(accessKeyID, secretAccessKey, ""),
})
if err != nil {
log.Fatalf("unable to create AWS session, %v", err)
}
s3Client = s3.New(sess)
}
func UploadToS3(content []byte, fileName, mimeType string) (string, error) {
_, err := s3Client.PutObject(&s3.PutObjectInput{
Bucket: aws.String(bucket),
Key: aws.String(fileName),
Body: bytes.NewReader(content),
ContentType: aws.String(mimeType),
})
if err != nil {
return "", fmt.Errorf("failed to upload file to S3, %v", err)
}
return fmt.Sprintf("https://%s.s3.amazonaws.com/%s", bucket, fileName), nil
}