Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

S3 uploading and serving image with pre signed URL

Tags:

amazon-s3

I am trying to upload an image to my S3 bucket through a pre-signed url. Everything works well except that when I hit the public URL for that image, the browser downloads it instead of showing it. When I upload the same image from the AWS Console, everything works well and the image gets displayed in the browser.

Here how I do it:

Generation of the pre-signed URL:

s3.getSignedUrl('putObject', {
    Bucket: myBucket,
    Key: myKey,
    Expires: signedUrlExpireSeconds
})

Upload of the file with axios:

const response = await axios.put(url, formElement.files[0])

Should I configure headers somewhere in the process to tell S3 the mime type of the content I'm uploading or something like this?

Thank you for your help

like image 779
Hammerbot Avatar asked Dec 07 '25 04:12

Hammerbot


1 Answers

There are two places you can do this.

If you know the type of image ahead of time, then you can explicitly set the ContentType in the s3.getSignedUrl params. This is because those params will be encoded and passed with the signed put request: getSignedUrl docs / putObject docs. So for example:

s3.getSignedUrl('putObject', {
    Bucket: myBucket,
    Key: myKey,
    Expires: signedUrlExpireSeconds,
    ContentType: 'image/png'
});

Alternatively, you can set the Content-Type header on the Axios request REST PUT docs, for example:

const response = await axios.put(
  url,
  formElement.files[0],
  { headers: { 'Content-Type': formElement.files[0].type } });
like image 136
thomasmichaelwallace Avatar answered Dec 10 '25 00:12

thomasmichaelwallace