4 回答
TA贡献1877条经验 获得超1个赞
在您的代码之后尝试一下:
import "github.com/aws/aws-sdk-go/private/protocol/rest"
...
req, _ := s3.New(s).GetObjectRequest(&s3.GetObjectInput{
Bucket: aws.String("bucket"),
Key: aws.String(tempFileName),
})
rest.Build(req)
uploadedResourceLocation := req.HTTPRequest.URL.String()
TA贡献1886条经验 获得超2个赞
您可以将 URL 构造为:
https://BUCKETNAME.s3-REGIONNAME.amazonaws.com/KEY
例如:
https://my-bucket.s3-ap-southeast-2.amazonaws.com/foo/bar.txt
TA贡献1868条经验 获得超4个赞
您可以借助以下代码获取上传的S3对象的路径。
import (
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/feature/s3/manager"
"github.com/aws/aws-sdk-go-v2/service/s3"
"github.com/aws/aws-sdk-go-v2/config"
"github.com/aws/aws-sdk-go-v2/credentials"
)
...
func configS3() *s3.Client {
creds := credentials.NewStaticCredentialsProvider(os.Getenv("ACCESS_KEY_ID"), os.Getenv("SECRET_ACCESS_KEY"), "")
cfg, err := config.LoadDefaultConfig(context.TODO(), config.WithCredentialsProvider(creds), config.WithRegion(os.Getenv("S3_REGION")))
if err != nil {
log.Fatal(err)
} else {
fmt.Println(" S3 has been initializd ! ")
}
return s3.NewFromConfig(cfg)
}
func UploadImageToS3(imageFile string) error {
// Open the file from the file path
upFile, err := os.Open(imageFile)
if err != nil {
return fmt.Errorf("could not open local filepath [%v]: %+v", imageFile, err)
}
defer upFile.Close()
uploader := manager.NewUploader(configS3())
uploadResult, err := uploader.Upload(context.TODO(), &s3.PutObjectInput{
Bucket: aws.String("BubblyBucket"),
Key: aws.String("folder1/Image.jpeg"),
Body: upFile,
ContentType: aws.String("image/jpg"),
})
if err != nil {
fmt.Printf("Error: %v \n", err)
return err
}
fmt.Println("Location: " + uploadResult.Location)
fmt.Printf("Image has been uploaded ->>> %v \t \n", imageFile)
return nil
}
结果会是这样的
Location: https://BubblyBucket.s3.ap-southeast-1.amazonaws.com/folder1/Image.jpeg
Image has been uploaded ->>> /home/my-machine/Pictures/Image-1.jpeg
- 4 回答
- 0 关注
- 348 浏览
添加回答
举报