使用 Go 将文件上传到 AWS S3
将大型多部分/表单数据文件直接流式传输到 AWS S3 是一种有效的方法,可以最大程度地减少内存使用情况和文件磁盘
解决方案
利用 AWS SDK for Go 的上传管理器将文件直接流式传输到 S3。下面是一个示例:
package main import ( "fmt" "os" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) var ( filename = "file_name.zip" myBucket = "myBucket" myKey = "file_name.zip" accessKey = "" accessSecret = "" ) func main() { var awsConfig *aws.Config if accessKey == "" || accessSecret == "" { awsConfig = &aws.Config{ Region: aws.String("us-west-2"), } } else { awsConfig = &aws.Config{ Region: aws.String("us-west-2"), Credentials: credentials.NewStaticCredentials(accessKey, accessSecret, ""), } } sess := session.Must(session.NewSession(awsConfig)) uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) { u.PartSize = 5 * 1024 * 1024 u.Concurrency = 2 }) f, err := os.Open(filename) if err != nil { fmt.Printf("failed to open file %q, %v", filename, err) return } defer f.Close() result, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String(myBucket), Key: aws.String(myKey), Body: f, }) if err != nil { fmt.Printf("failed to upload file, %v", err) return } fmt.Printf("file uploaded to, %s\n", result.Location) }
通过使用具有自定义参数的上传管理器,您可以配置部分大小、并发级别和最大上传部分计数,以优化流处理。
以上是如何使用 Go 高效地将大型多部分/表单数据文件流式传输到 AWS S3?的详细内容。更多信息请关注PHP中文网其他相关文章!