How to get public url after uploading image to S3?
Your application should be using some configuration/properties file, where the name of the bucket is stored for later reference. Use, for example, a properties file with a properties defined like this:
application.bucket=mybucket-example-com
Use this value both when referencing the bucket in your app (eg replace _bucket
with application.bucket
in your code), and when you want to express or return the public URL.
If your app has uploaded a file to the key userid/images/test.jpg
, then the public URL can be expressed as:
https://[application.bucket].s3.amazonaws.com/[key]
This will resolve to the public URL of
https://mybucket-example-com.s3.amazonaws.com/userid/images/test.jpg
The nice thing about this approach is that in your testing environment, you can have a different bucket specified in your test configuration.
In testing, you may want to use application.bucket=test-mybucket-example-com
.
This way your code would not require any changes in this regard when switching between production and testing environments.
You could actually build this url based on the bucket name and the path where you uploaded the file. See this doc about accessing a bucket, where it describes the url format.
e.g:
https://bucket.s3.amazonaws.com/path/to/your/file
https://bucket.s3-aws-region.amazonaws.com/path/to/your/file
https://s3-aws-region.amazonaws.com/bucket/path/to/your/file
Please note that your file must be public, otherwise you will get a permission denied.
Note: the path-style (https://s3-aws-region.amazonaws.com/bucket/path/to/your/file
is now deprecated and should not be used anymore