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",
})
}
})