Thursday, 1 June 2017

how to show images from s3 instead of downloading them?

I'm using Amazon s3 to serve images, and I'm using getSignedUrl to upload images from the browser.

Problem

the problem is some images are not being shown in the browser but instead, they auto downloaded. even with the propriety ContentType there while creating the singedUrl

Code

Here a small service that return a signedUrl

module.exports = ({ type }) => {
  const s3 = new aws.S3({ signatureVersion: 'v4' })
  const fileType = type

  return new Promise((resolve, reject) => {
    if (!fileType) {
      return reject({ message: 'fail type is required' })
    }
    const fileName = `${_.uniqueId(`xcuf_${_.now()}`)}.${fileType.split('/')[1]}`
    const s3Params = {
      Bucket: `${BUCKET_NAME}`,
      Key: fileName,
      Expires: 120,
      ACL: 'public-read',
      ContentType: fileType
    }

    return s3.getSignedUrl('putObject', s3Params, (err, data) => {
      if (err) {
        return reject(err)
      }
      return resolve({
        signedRequest: data,
        url: `https://${BUCKET_NAME}.s3.amazonaws.com/${fileName}`
      })
    })
  })
}



via Gintoki

No comments:

Post a Comment