将大型文件直接上传到 AWS S3,同时最大限度地减少内存和磁盘占用空间是一项重要任务在云计算中。本指南将演示如何使用适用于 Go 的 AWS 开发工具包来实现此目的。
要将文件上传直接流式传输到 S3,您可以使用 s3manager 包。以下是分步解决方案:
配置 AWS 凭证和会话:
创建 S3 上传器:
打开文件:
上传文件:
以下代码示例演示了如何使用流式传输大文件上传到 AWS S3 s3manager:
package main import ( "fmt" "os" "github.com/aws/aws-sdk-go/aws/credentials" "github.com/aws/aws-sdk-go/aws" "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) const ( filename = "file_name.zip" myBucket = "myBucket" myKey = "file_name.zip" accessKey = "" accessSecret = "" ) func main() { var awsConfig *aws.Config if accessKey == "" || accessSecret == "" { //load default credentials awsConfig = &aws.Config{ Region: aws.String("us-west-2"), } } else { awsConfig = &aws.Config{ Region: aws.String("us-west-2"), Credentials: credentials.NewStaticCredentials(accessKey, accessSecret, ""), } } // The session the S3 Uploader will use sess := session.Must(session.NewSession(awsConfig)) // Create an uploader with the session and default options //uploader := s3manager.NewUploader(sess) // Create an uploader with the session and custom options uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) { u.PartSize = 5 * 1024 * 1024 // The minimum/default allowed part size is 5MB u.Concurrency = 2 // default is 5 }) //open the file f, err := os.Open(filename) if err != nil { fmt.Printf("failed to open file %q, %v", filename, err) return } //defer f.Close() // Upload the file to S3. result, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String(myBucket), Key: aws.String(myKey), Body: f, }) //in case it fails to upload if err != nil { fmt.Printf("failed to upload file, %v", err) return } fmt.Printf("file uploaded to, %s\n", result.Location) }
通过执行这些步骤,您可以高效地将大型多部分/表单数据文件直接上传到 AWS S3,同时占用最少的内存。
免责声明: 提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发到邮箱:[email protected] 我们会第一时间内为您处理。
Copyright© 2022 湘ICP备2022001581号-3