Categories
JavaScript Answers

How to add simple file upload to S3 using aws-sdk and Node/Express?

Spread the love

To add simple file upload to S3 using aws-sdk and Node/Express, we use the multer-s3 package.

For instance, we write

const express = require("express"),
  bodyParser = require("body-parser"),
  multer = require("multer"),
  s3 = require("multer-s3");

const app = express();

app.use(bodyParser.json());

const upload = multer({
  storage: s3({
    dirname: "/",
    bucket: "bucket-name",
    secretAccessKey: "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
    accessKeyId: "XXXXXXXXXXXXXXX",
    region: "us-east-1",
    filename: (req, file, cb) => {
      cb(null, file.originalname);
    },
  }),
});

app.get("/", (req, res) => {
  res.sendFile(__dirname + "/index.html");
});

app.post("/upload", upload.array("upl"), (req, res, next) => {
  res.send("Uploaded!");
});

app.listen(3000, () => {
  console.log("Example app listening on port 3000!");
});

to call multer with an object that has storage set to the storage object created by s3.

We call s3 with an object with the AWS credentials, the region and the filename method to set the file name.

bucket has the bucket name. dirname is the upload file folder.

We call upload.array with the key name of the form data entry with the files to return the middleware to let us accept upload files.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *