Get URL(link) of a public S3 object programmatically

后端 未结 7 669
心在旅途
心在旅途 2021-01-01 14:06

I am storing one public object in AWS S3 bucket using given java API in my server Now i need to return back the public URL of the S3 object to my client

Till now i h

相关标签:
7条回答
  • 2021-01-01 14:32
    s3Client.getUrl(AWS_BUCKET, s3RelativeFilePath).toExternalForm();    
    

    older versions had:

    s3Client.getResourceUrl(bucket, s3RelativeToBucketPath);
    
    0 讨论(0)
  • 2021-01-01 14:40
    "https://"+{bucket}.s3.amazonaws.com+"/"+key
    

    This URL may look different from the link in object overview in S3. But it works just as the same. Note: The link in object overview usually looks like

      https://s3-ap-southeast-2.amazonaws.com/{bucket}/{key}
    
    0 讨论(0)
  • "https://s3.amazonaws.com/"+bucketName+"/"+key should give you the url to the object in s3

    0 讨论(0)
  • 2021-01-01 14:45

    For users, who have private buckets and requires the URL.

    In my case, I had to get downloadable link of S3 Object for a specific time as my bucket is private.

    I'm using Spring Cloud AWS, which under the hood uses AWS SDK For Java and which provides AmazonS3 interface for interacting with S3, use AmazonS3Client if you're using AWS SDK For JAVA instead of AmazonS3. I simply injected AmazonS3 and now I can get URL of an object where-ever required, but it can be downloaded within 5 mins else it will be expired.

     public String getURL(String key) throws FileNotFoundException
    {
        try {
            return amazonS3.generatePresignedUrl(BUCKET_NAME, key, new DateTime().plusMinutes(5).toDate()).toString();
        }
        catch (AmazonS3Exception exception){
            if(exception.getStatusCode() == 404){
                throw new FileNotFoundException(key);
            }
            else{
                throw exception;
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-01 14:55

    i am using aws-java-sdk-s3 1.11.58

    accepted answer not working on this version.

    below line works for this version

    s3Client.getUrl(AWS_BUCKET, s3RelativeFilePath).toExternalForm();
    
    0 讨论(0)
  • 2021-01-01 14:55

    Consider constructing the url using bucket name and object key instead of making a request to s3 everytime to just fetch the url.

    0 讨论(0)
提交回复
热议问题