j roc
j roc

Reputation: 238

Uploading images to s3 using node.js

This is my first time ever using multer or s3, I followed along with a blog and I seem to be running into some issues. In my routes.js when I return res.json({'imageUrl': req.file.location}) I get this error: Cannot read property 'location' of undefined and when I console.log() req.file it returns undefined.

I'm confident that my bucket and all that is configured correctly, I'm just a bit confused as to what's going on in the code. I would really appreciate if someone could point out what I'm doing wrong or has any suggestions

Thanks!

update: I can successfully upload images through postman, but not the form in my project. I'm pretty sure my problem is coming from return res.json({'imageUrl': req.file.location})

// uploadController.js


const aws = require("aws-sdk");
const multer = require("multer");
const multerS3 = require("multer-s3");
require("dotenv").config();

aws.config.update({
  secretAccessKey: process.env.SECRETACCESSKEY,
  accessKeyId: process.env.ACCESSKEYID,
  region: "us-west-2",
});
const s3 = new aws.S3();

const fileFilter = (req, file, cb) => {
  if (file.mimetype === "image/jpeg" || file.mimetype === "image/png") {
    cb(null, true);
  } else {
    cb(new Error("Invalid mime type, only JPEG and PNG"), false);
  }
};

const upload = multer({
  fileFilter: fileFilter,
  storage: multerS3({
    s3: s3,
    bucket: "mylocal",
    acl: "public-read",
    metadata: function (req, file, cb) {
      cb(null, { fieldName: "TESTING_META_DATA" });
    },
    key: function (req, file, cb) {
      cb(null, Date.now().toString());
    },
  }),
});


module.exports = upload;

 // routes.js

let upload = require('../controllers/uploadController')


router.get("/upload", function (req, res) {
  res.render("upload");
});

const singleUpload = upload.single("image");

router.post("/upload", function (req, res) {
  singleUpload(req, res, function (err) {
    if (err) {
      return res.status(422).send({ errors: "wrong" });
    }
    console.log(req.file); // returns undefined
    return res.json({'imageUrl': req.file.location})
   
  });
});

// upload.ejs

 <form method="POST" enctype="multipart/form-data">
      <input type="file" />
      <button type="submit">upload</button>
    </form>

Upvotes: 0

Views: 331

Answers (1)

Sayeed A P
Sayeed A P

Reputation: 51

Try req.files(please note s at the end) Instead of req.file

Upvotes: 1

Related Questions