Hi,
I am trying to upload a local image file to an AWS S3 bucket and return the public URL in Golang. This is the core Golang code I have written to interact with my S3 bucket:
creds := credentials.NewSharedCredentials("/Users/username/.aws/credentials", "default")
config := &aws.Config{
Region: aws.String("us-west-2"),
Credentials: creds,
}
sess := session.New(config)
uploader := s3manager.NewUploader(sess, func(u *s3manager.Uploader) {
u.PartSize = 64 * 1024 * 1024
u.LeavePartsOnError = true
})
fmt.Println(header.Filename)
fileInfo, _ := out.Stat()
var size int64 = fileInfo.Size()
fmt.Println("size", size)
buffer := make([]byte, size)
out.Read(buffer)
fileBytes := bytes.NewReader(buffer)
result, err := uploader.Upload(&s3manager.UploadInput{
Bucket: aws.String("bucket-name"),
Key: aws.String(header.Filename),
Body: aws.ReadSeekCloser(fileBytes),
ContentType: aws.String("image/jpeg"),
ACL: aws.String("public-read"),
})
if err != nil || result == nil {
log.Fatalln("Failed to upload", err)
}
log.Println("Successfully uploaded to", result.Location)
With this code, the file is uploaded successfully to my s3 bucket with the correct size in bytes, but when I click on the URL, a black square is displayed instead of the actual image. If I change the ContentType field to allow file types dynamically, when I click on the URL, it downloads the image, but the image cannot be opened because "it may have been damaged." How can I fix this Golang code to just upload an image to an S3 bucket and get the public URL as a result of that upload?
This may be more of a debugging question pertaining to AWS S3 than Golang, but any help would be appreciated. Thank you!