Skip to content

Instantly share code, notes, and snippets.

@bre7
Created February 10, 2021 19:46
Show Gist options
  • Save bre7/bbe045a3ba8fa762241bde863476da53 to your computer and use it in GitHub Desktop.
Save bre7/bbe045a3ba8fa762241bde863476da53 to your computer and use it in GitHub Desktop.
aws-sdk-js-v3 S3 simple how-to guide

Just a really simple guide on using S3 aws-sdk-js-v3 / @aws-sdk/client-s3 Assuming @aws-sdk/client-s3 is installed:

How to stream file from S3 to Express

import { S3 } from "@aws-sdk/client-s3"

express.get(`/file/:id`, async (req, res) => {
  const s3 = new S3({
    credentials: {
      accessKeyId: "aaa",
      secretAccessKey: "bbb",
    },
    region: "us-east-1", // TODO: Change if needed
  })

  try {
    const fileObject = await s3.getObject({
      Bucket: "xxxxx",
      Key: "xxxxx",
    })

    // optional
    res.setHeader("Content-Disposition", `inline; filename="${filename}"`)
    
    if (fileObject.Body && fileObject.Body instanceof Readable) {
      fileObject.Body.pipe(res)
    } else {
      throw new Error('Unknown object stream type');
    }
  } catch (e) {
    console.error(e)
    
    return res.status(403).json({
      "error": "oops",
    })
  }
)}

How to upload to S3

import { S3 } from "@aws-sdk/client-s3"
import { UploadedFile } from "express-fileupload"
import { Readable } from "stream"
import mime from "mime-types"

express.put(`/files`, async (req, res) => {
  const s3 = new S3({
    credentials: {
      accessKeyId: "aaa",
      secretAccessKey: "bbb",
    },
    region: "us-east-1", // TODO: Change if needed
  })
  
  // will upload first file only
  const uploadedFile = Object.values(req.files!).first()! as UploadedFile
  const filename = uploadedFile.name
  const fileContent = Buffer.from(uploadedFile.data)

  try {
    await s3.putObject({
      Bucket: "xxx",
      Key: "xxx",
      Body: fileContent,
      ContentType: mime.lookup(filename) || undefined,
    })
    
   // done
  } catch (e) {
    console.error(e)
    
    return res.status(403).json({
      "error": "oops",
    })
  }
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment