在 Go 中将文件放入 amazon s3 后如何获取文件 url?

文件上传成功,上传后我想返回文件url。


_, err := s3.New(s).PutObject(&s3.PutObjectInput{

    Bucket:               aws.String("bucket"),

    Key:                  aws.String(tempFileName),

    ACL:                  aws.String("public-read"), // could be private if you want it to be access by only authorized users

    Body:                 bytes.NewReader(buffer),

    ContentLength:        aws.Int64(int64(size)),

    ContentType:          aws.String(http.DetectContentType(buffer)),

    ContentDisposition:   aws.String("attachment"),

    ServerSideEncryption: aws.String("AES256"),

    StorageClass:         aws.String("INTELLIGENT_TIERING"),

})

我已经检查了亚马逊文档中的 PutObject 函数,但是 PutObjectOutput 结构类型 但此结构中没有上传的文件 url。


我怎样才能获取文件的url?上传成功后是否有其他方法在 amazon s3 sdk 中返回上传的文件 url?


谢谢


胡子哥哥
浏览 379回答 4
4回答

冉冉说

在您的代码之后尝试一下: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()

MM们

您可以将 URL 构造为:https://BUCKETNAME.s3-REGIONNAME.amazonaws.com/KEY例如:https://my-bucket.s3-ap-southeast-2.amazonaws.com/foo/bar.txt

拉风的咖菲猫

您需要重建文件 url使用您上传文件的 s3 路径 + 文件名

MYYA

您可以借助以下代码获取上传的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     
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go