使用 Go 将文件上传到 AWS S3
挑战:
流式传输大型分段/form-data 文件直接传输到 AWS S3,最大限度地减少内存和磁盘占用。
解决方案:
为了实现此目的,我们将使用 github 中的 S3 上传器.com/aws/aws-sdk-go 库。
实现:
示例代码:
import ( "github.com/aws/aws-sdk-go/aws/session" "github.com/aws/aws-sdk-go/service/s3/s3manager" ) func main() { // Create an S3 uploader with custom options uploader := s3manager.NewUploader(session.Must(session.NewSession()), func(u *s3manager.Uploader) { u.PartSize = 5 * 1024 * 1024 // 5MB part size u.Concurrency = 2 // 2 concurrent uploads }) // Open the file for upload f, err := os.Open("file.txt") if err != nil { panic(err) } defer f.Close() // Stream file to S3 result, err := uploader.Upload(&s3manager.UploadInput{ Bucket: aws.String("my-bucket"), Key: aws.String("file.txt"), Body: f, }) if err != nil { panic(err) } // Display uploaded file information fmt.Printf("File uploaded to: %s", result.Location) }
以上是如何使用 Go 将大文件流式传输到 AWS S3?的详细内容。更多信息请关注PHP中文网其他相关文章!