Skip to content

Instantly share code, notes, and snippets.

@i-mighty
Created December 10, 2020 07:30
Show Gist options
  • Save i-mighty/598a781dc2102e35ed717ccbc7a10199 to your computer and use it in GitHub Desktop.
Save i-mighty/598a781dc2102e35ed717ccbc7a10199 to your computer and use it in GitHub Desktop.
AWS S3 Node.js example.
Read up the docs on how to setup the cli.
If you need to setup for pipeline or for production without the CLI, you would need to make some modification to the code.
Blessings
//Assuming this is your entry file
import express from "express";
//Other imports
import fileUpload from "express-fileupload";
export const app = express();
app.use(
fileUpload({
debug: true,
}),
);
//Add other express middlewares, services and proxies
import { RequestHandler } from "express";
import { $S3 } from "s3/service/import/path";
export const uploadEcpDocumentController: RequestHandler = async (
req,
res,
next,
) => {
const file = req.files?.fileField; // Request would be multipart so it would be fileField would be name of the field.
const key = 'someRandomStringToUseAsYourAWSKey';
const document = await new $S3().uploadPrivateFile(file, key);
//document is of the type ManagedUpload.SendData. Should read up that one.
//Do whatever you would with the response. Normally format and return a response.
}
//This example is going to assume you've setup your /home/user/.aws/config /home/user/.aws/credential files well
import { S3 } from "aws-sdk";
export class $S3 {
_s3: S3 = new S3();
async uploadPrivateFile(file?: UploadedFile, key?: string) {
if (file) {
const upload = await this._s3
.upload({
Bucket: process.env.AWS_BUCKET || "",
Body: file.data,
Key: key || "",
})
.promise()
.then((data) => {
return data;
});
return upload;
} else {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment