Get URL(link) of a public S3 object programmatically

后端 未结 7 725
心在旅途
心在旅途 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: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;
            }
        }
    }
    

提交回复
热议问题