Sending a file directly from the browser to S3, but changing the file name

I use a signed S3 authorized download so that users can upload files directly from their browser to S3 bypassing my server. This currently works, but the file name matches the username. I would like to save it on S3 as another name.

The forms I submit to amazon look like this:

var formData = new FormData(); formData.append('key', targetPath); // eg /path/inside/bucket/myFile.mov formData.append('AWSAccessKeyId', s3Auth.AWSAccessKeyId); // aws public key formData.append('acl', s3Auth.acl); // eg 'public-read' formData.append('policy', s3Auth.policy); // s3 policy including ['starts-with', '$key', '/path/inside/bucket/'] formData.append('signature', s3Auth.signature); // base64 sha1 hash of private key and base64 policy JSON formData.append('success_action_status ', 200); // response code 200 on success formData.append('file', file.slice()); // eg /path/on/user/computer/theirFile.mov 

However, instead of a file ending in: https://s3.amazonaws.com/mybucket/path/inside/bucket/myFile.mov

It ends as: https://s3.amazonaws.com/mybucket/path/inside/bucket/theirFile.mov

Note that it has a file name, but my base path.

I would like it to have a file name, which I also specify.

Update: Update: this worked all the time. I just had a different code copied from one bucket to another, which restored the original file name and thus confused me.

+6
source share
1 answer

Are you sure about the content of targetPath and where targetPath this data come from?

The behavior you describe should occur in one specific case where targetPath does not actually contain /path/inside/bucket/myFile.mov .

I would suggest that targetPath really contains the value /path/inside/bucket/${filename} - and by that I mean that literally $ { filename } characters $ { filename } are at the end of this line, and not the name of the file that you mean.

If so, then exactly how it should work.

If you do not know the name of the file that will be downloaded by the user, the key value may include the special variable ${filename} , which will be replaced by the name of the downloaded file. For example, the value of the uploads/${filename} key will become the name of the uploads/Birthday Cake.jpg if the user uploads/Birthday Cake.jpg file called Birthday Cake.jpg .

- https://aws.amazon.com/articles/1434

If you fill this variable with the literal name of the file that you want to see on S3, then the download should behave as you would expect, using the file name instead of the file name on the bootloader.


In addition, a safer approach would be to eliminate the 'starts-with' key logic in your policy and instead explicitly sign the policy (dynamically) for each download event, with a specific key that you want to load to the user. Otherwise, it is impossible to use this form to overwrite other files in the same key prefix.

+4
source

Source: https://habr.com/ru/post/976787/


All Articles