Search code examples
javascriptnode.jsamazon-s3pre-signed-urlfile-storage

How to limit file's size and mimetype on upload to S3


On my application I save all user's images on Amazon S3. I'm realizing a web interface for uploading images to S3.

On my nodejs backend I'm creating presigned post request:

const presignedPostParams = ({ userId }) => ({
  Bucket: bucket,
  Conditions: [
    ['starts-with', '$key', `user/${userId}/`],
  ],
  Expires: 60 * 5,
});

  const request = await createPresignedPost(presignedPostParams({ userId }));

On my frontend I'm sending a form to S3 with presigned params.

It works.

But now I can upload any files, not only images. I want to limit file types to upload (mimetypes)? Of course, I can limit it by javascript code on front. By it is not reliable.

Can I limit file mimetype while I'm creating presigned url?

And the second question: can I manage the permission of uploaded file from presigned url? I want upload some public and some private files from one interface (maybe I can realize this with presigned url?)


Solution

  • I've got the answer to the second question.

    It's very easy, but I haven't found it in the documentation.

    I added one condition to the backend (about this I read on docs):

      Conditions: [
        { acl: 'public-read' },
        // ...
      ],
    

    and added one field to the frontend: 'acl': 'public-read'

    (I found it by chance surfing by links on POST Policy documentation )


    About file's size: Its easy, too: You should add one condition: ["content-length-range", 1048579, 10485760]