'Multer S3 image file upload not receiving req.file from React app as expected

I am trying to upload an image from a react app to a Node.js backend but I am unable to get it to work.

Here is my front end function:

const handleImage = async (e) => {
    var formData = new FormData();;
    let file = e.target.files[0];

    formData.append("file", file);

    try {
      const upload = await fetch(
        `${process.env.NEXT_PUBLIC_SERVER_API}/uploadImage`,
        {
          method: "POST",
          body: formData,
        }
      );
    } catch (e) {
      console.log("Something went wrong!");
    }
  };

The html form tag contains the following:

<form
  onSubmit={handlePostSubmit}
  enctype="multipart/form-data"
  method="post"
 >

On the backend, I have the following code:

var aws = require("aws-sdk");
var multer = require("multer");
var multerS3 = require("multer-s3");

aws.config.update({
  secretAccessKey: process.env.S3_SECRET_ACCESS_KEY,
  accessKeyId: process.env.S3_ACCESS_KEY_ID,
  region: process.env.S3_REGION,
});

const s3 = new aws.S3();

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

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

router.post("/uploadImage", function (req, res) {
  singleUpload(req, res, function (err, some) {
    console.log("FILE", req.file)
    if (err) {
      return res.status(422).send({
        errors: [{ title: "Image Upload Error", detail: err.message }],
      });
    }
    return res.json({ imageUrl: req.file.location });
  });
});

When I log to the console in the singleUpload function, I receive undefined.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source