简体   繁体   中英

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.

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.

@Alexa,

You will need to pass the file name in the Key instead of random hash

eg

url = client.generate_presigned_url(
       ClientMethod = 'get_object',
       Params = {
          'Bucket': 'bucketname',
          'key': 'test.pdf'
      }

   )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM