使用Go 將檔案上傳到AWS S3
將大型多部分/表單資料檔案直接串流到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中文網其他相關文章!