【发布时间】:2020-04-21 09:14:52
【问题描述】:
我正在尝试使用 golang sdk 将对象上传到 AWS S3,而无需在我的系统中创建文件(尝试仅上传字符串)。但我很难做到这一点。谁能给我一个示例,说明如何在无需创建文件的情况下上传到 AWS S3?
AWS 上传文件示例:
// Creates a S3 Bucket in the region configured in the shared config
// or AWS_REGION environment variable.
//
// Usage:
// go run s3_upload_object.go BUCKET_NAME FILENAME
func main() {
if len(os.Args) != 3 {
exitErrorf("bucket and file name required\nUsage: %s bucket_name filename",
os.Args[0])
}
bucket := os.Args[1]
filename := os.Args[2]
file, err := os.Open(filename)
if err != nil {
exitErrorf("Unable to open file %q, %v", err)
}
defer file.Close()
// Initialize a session in us-west-2 that the SDK will use to load
// credentials from the shared credentials file ~/.aws/credentials.
sess, err := session.NewSession(&aws.Config{
Region: aws.String("us-west-2")},
)
// Setup the S3 Upload Manager. Also see the SDK doc for the Upload Manager
// for more information on configuring part size, and concurrency.
//
// http://docs.aws.amazon.com/sdk-for-go/api/service/s3/s3manager/#NewUploader
uploader := s3manager.NewUploader(sess)
// Upload the file's body to S3 bucket as an object with the key being the
// same as the filename.
_, err = uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String(bucket),
// Can also use the `filepath` standard library package to modify the
// filename as need for an S3 object key. Such as turning absolute path
// to a relative path.
Key: aws.String(filename),
// The file to be uploaded. io.ReadSeeker is preferred as the Uploader
// will be able to optimize memory when uploading large content. io.Reader
// is supported, but will require buffering of the reader's bytes for
// each part.
Body: file,
})
if err != nil {
// Print the error and exit.
exitErrorf("Unable to upload %q to %q, %v", filename, bucket, err)
}
fmt.Printf("Successfully uploaded %q to %q\n", filename, bucket)
}
我已经尝试以编程方式创建文件,但它正在我的系统上创建文件,然后将其上传到 S3。
【问题讨论】:
-
发布你已经尝试过的事情。
-
我只是尝试按照 AWS 的示例进行操作。从您的系统打开一个文件并将其上传到 S3。我将使用示例编辑问题。我的错。
-
显示您要上传的内容。 s3manager.UploadInput.Body 是一个 io.Reader。使用 bytes.NewReader、strings.NewReader、bytes.Buffer 或任何其他数量的支持接口的类型创建 io.Reader。
-
@CeriseLimón 我认为这将解决我的问题我如此专注于文件,以至于我没有意识到 s3manager.UploadInput.Body 和 io.Reader。完全是我的错。我现在正在测试它,我会在这里发布结果。
-
@EricReisFigueiredo 你能发布你是如何使用 io.Reader 的答案
标签: go amazon-s3 aws-sdk-go