使用Go 中的上傳管理器可以將大檔案直接上傳到AWS S3,同時最小化記憶體和檔案磁碟佔用空間。操作方法如下:
匯入必要的函式庫:
import ( "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" )
建立AWS 配置:
awsConfig := &aws.Config{ Region: aws.String("us-west-2"), }
如果需要,您可以選擇在設定中提供自己的存取金鑰和秘密金鑰。
初始化新會話和上傳器:
sess := session.Must(session.NewSession(awsConfig)) uploader := s3manager.NewUploader(sess)
自訂上傳器參數(選購):
// Set the part size, concurrency, and max upload parts uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) { u.PartSize = 5 * 1024 * 1024 // 5MB is the minimum allowed part size u.Concurrency = 2 // Default is 5 })
f, err := os.Open(filename) if err != nil { fmt.Printf("failed to open file %q, %v\n", filename, err) return }
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\n", err) return }
使用上傳器上傳檔案:
fmt.Printf("file uploaded to, %s\n", result.Location)
以上是如何使用 Go 將檔案上傳到 AWS S3?的詳細內容。更多資訊請關注PHP中文網其他相關文章!