Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Upload to Amazon S3 using Boto3 and return public url

Iam trying to upload files to s3 using Boto3 and make that uploaded file public and return it as a url.

class UtilResource(BaseZMPResource): class Meta(BaseZMPResource.Meta):     queryset = Configuration.objects.none()     resource_name = 'util_resource'     allowed_methods = ['get']  def post_list(self, request, **kwargs):      fileToUpload = request.FILES     # write code to upload to amazone s3     # see: https://boto3.readthedocs.org/en/latest/reference/services/s3.html       self.session = Session(aws_access_key_id=settings.AWS_KEY_ID,                   aws_secret_access_key=settings.AWS_ACCESS_KEY,                   region_name=settings.AWS_REGION)      client = self.session.client('s3')     client.upload_file('zango-static','fileToUpload')       url = "some/test/url"     return self.create_response(request, {         'url': url // return's public url of uploaded file      }) 

I searched whole documentation I couldn't find any links which describes how to do this can someone explain or provide any resource where I can find the soultion?

like image 839
Yaswanth Kumar Avatar asked Nov 19 '15 16:11

Yaswanth Kumar


People also ask

How do I get my S3 upload URL?

You can get the resource URL either by calling getResourceUrl or getUrl . AmazonS3Client s3Client = (AmazonS3Client)AmazonS3ClientBuilder. defaultClient(); s3Client. putObject(new PutObjectRequest("your-bucket", "some-path/some-key.

How do I find my public S3 bucket URL?

Get an S3 Object's URL #Navigate to the AWS S3 console and click on your bucket's name. Use the search input to find the object if necessary. Click on the checkbox next to the object's name. Click on the Copy URL button.

Can you upload to public S3 bucket?

You can have an unlimited number of objects in a bucket. Before you can upload files to an Amazon S3 bucket, you need write permissions for the bucket. For more information about access permissions, see Identity and access management in Amazon S3. You can upload any file type—images, backups, data, movies, etc.


1 Answers

I'm in the same situation. Not able to find anything in the Boto3 docs beyond generate_presigned_url which is not what I need in my case since I have public readable S3 Objects.

The best I came up with is:

bucket_location = boto3.client('s3').get_bucket_location(Bucket=s3_bucket_name) object_url = "https://s3-{0}.amazonaws.com/{1}/{2}".format(     bucket_location['LocationConstraint'],     s3_bucket_name,     key_name) 

You might try posting on the boto3 github issues list for a better solution.

like image 127
Sam Keen Avatar answered Nov 10 '22 14:11

Sam Keen