How to send files to a static website on S3

Asked

Viewed 38 times

0

I’m developing an application in Nodejs using the AWS SDK. Summarizing the code creates a Bucket, assigns the security policies to allow public access, and enables it to static websites however, when sending the files via SDK when accessing the website address the content is downloaded to the PC and not loaded in the browser.

Note: if the files are sent directly from the AWS console the site works correctly.

Does anyone have an idea of how I can solve this problem? I did several searches and so far I could not find the solution.

exports.createObject = (req, res) => {
    return new Promise((resolve, reject) => {
        const s3 = new S3Client({
            region: req.body.region
        })

        async function run() {

            try {

                const indexHTML = path.resolve('exPages', 'index.html')
                let fileContent = fs.readFileSync(indexHTML)

                let params = {
                    Bucket: req.body.bucket,
                    Key: path.basename(indexHTML),
                    Body: fileContent,
                }

                _Display.line()
                console.log(chalk.blueBright('Request - Upload files'))
                _Display.line()
                let data = await s3.send(new PutObjectCommand(params))
                console.log(chalk.gray('Upload complete'))
                console.log('')
                console.log('', data)
                resolve(data)

            } catch (error) {
                console.log('Erro', error)
                reject(error)
            }
        }
        run()
    })
}

1 answer

1

When uploading images you need to configure the ContentType as image/jpeg, otherwise they rise as binary/octet-stream and do not behave as you wish.

let params = {
    Bucket: req.body.bucket,
    Key: path.basename(indexHTML),
    Body: fileContent,
    ContentType: "image/jpg",
}

EDIT:

Enabling static hosting on S3:

You need to go on the tab Properties inside the Bucket and below on Static website hosting enable the static hosting.

Then your read-only html files will be accessible at: https://{yourBucket}.S3-{his-region}.amazonaws.with/{your-file}


reference: https://docs.aws.amazon.com/AmazonS3/latest/userguide/HostingWebsiteOnS3Setup.html

  • Leo, the files that are being uploaded are actually html type. I passed in Content Type "text/html" however the problem continues

  • Putz, sorry. I understood that you wanted to load the Assets. I will edit the answer.

  • Leo, first thanks for the help. I discovered that there was a typo in Contenttype: "text/html"

Browser other questions tagged

You are not signed in. Login or sign up in order to post.