Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use filename as name of file when downloading from s3 using boto3

I'm uploading a file using boto3 like this:

  client = boto3.client('s3', 
           aws_access_key_id = id, 
           aws_secret_access_key = key

  client.upload_file('tmp/test.pdf', 'bucketname', 'test.pdf')

Then I generate a download link using generate_presigned_url

   url = client.generate_presigned_url(
       ClientMethod = 'get_object',
       Params = {
          'Bucket': 'bucketname',
          'key': <randomhash>
      }

   )

When I download the file on the link it's named after the key which is a random unique hash - with no extension - I want to give it a specific filename with extension.How can I do that?

Edit: I understand I can use the filename as a key but my issue with this method is that if a users upload the similar filenames the url would link to incorrect/most recent files only. That's why I prefer using a unique hash.

The only drawback with using the unique hash is then my filename for downloading becomes some long hash instead of the filename I gave it when uploading.

like image 253
Alexa Avatar asked Dec 17 '22 17:12

Alexa


1 Answers

Add this key-value to your Params:

'ResponseContentDisposition': f"attachment; filename = {filename}"

This should set the Content-Disposition header of the download response so that the filename is set.

like image 68
dirkgroten Avatar answered Jan 14 '23 11:01

dirkgroten