以最少的内存和文件磁盘占用量将文件流式上传到 AWS S3
问题:您需要上传大型多部分/表单数据文件直接传输到 AWS S3,同时最大限度地减少内存和文件磁盘使用。
解决方案:通过以下步骤利用 AWS S3 上传器:
示例代码:
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" ) // Configure Amazon S3 credentials and connection var accessKey = "" var accessSecret = "" func main() { // Determine if your AWS credentials are configured globally var awsConfig *aws.Config if accessKey == "" || accessSecret == "" { // No credentials provided, load the default credentials awsConfig = &aws.Config{ Region: aws.String("us-west-2"), } } else { // Static credentials provided awsConfig = &aws.Config{ Region: aws.String("us-west-2"), Credentials: credentials.NewStaticCredentials(accessKey, accessSecret, ""), } } // Create an AWS session with the configured credentials sess := session.Must(session.NewSession(awsConfig)) // Create an uploader with customized configuration uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) { u.PartSize = 5 * 1024 * 1024 // Set the part size to 5MB u.Concurrency = 2 // Set the concurrency to 2 }) // Open the file to be uploaded f, err := os.Open("file_name.zip") if err != nil { fmt.Printf("Failed to open file: %v", err) return } defer f.Close() // Upload the file to S3 result, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String("myBucket"), Key: aws.String("file_name.zip"), Body: f, }) if err != nil { fmt.Printf("Failed to upload file: %v", err) return } fmt.Printf("File uploaded to: %s", result.Location) }
通过使用 S3 Uploader 并流式传输文件,您可以最大限度地减少上传过程中的内存和文件磁盘使用量,确保高效处理大文件。
以上是如何以最少的内存和磁盘使用量将大文件流式传输到 AWS S3?的详细内容。更多信息请关注PHP中文网其他相关文章!