将大文件直接上传到 AWS S3,同时最大限度地减少内存和磁盘占用空间是一项重要任务在云计算中。本指南将演示如何使用适用于 Go 的 AWS 开发工具包来实现此目的。
要将文件上传直接流式传输到 S3,您可以使用 s3manager 软件包。以下是分步解决方案:
配置 AWS 凭证和会话:
创建 S3 上传器:
打开文件:
上传文件:
以下代码示例演示了如何使用 s3manager 将大文件上传到 AWS S3:
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。
以上是如何使用 Go 将文件上传到 AWS S3?的详细内容。更多信息请关注PHP中文网其他相关文章!