0

I have a react application trying to upload multiple files using formdata. It seems to be able to do upload.single() but not upload.array() on the backend. And I cannot figure out why.

Function handling the upload when a button is clicked

  const handleUpload = async () => {
    let data = new FormData();
    data.append("files", imageList);
    data.append("title", title);
    data.append("short_text", shortText);
    data.append("news", news);
    const response = newsUpload(data);
    console.log(response);
  };

The api function on the front-end

export const newsUpload = async (data) => {
  return await api
    .post(`api/news/upload`, data)
    .then((data) => {
      return "DONE!";
    })
    .catch((err) => {
      console.log(err.response.data);
    });
};

Back-end: I instantiate the multer instance in the server.js file which is the run file.

var storage = multer.diskStorage({
  destination: function (req, file, cb) {
    cb(null, "uploads/");
  },
  filename: function (req, file, cb) {
    cb(null, req.userId + Date.now() + ".jpeg");
  },
});
const upload = multer({ storage: storage });

and I then send the upload function into the router:

require("./app/routes/news.routes")(app, upload);

news.routes.js defines the route for api/news/upload with the upload.array() being sent through:

app.post(
    "/api/news/upload",
    [authJwt.verifyToken, authJwt.isAdmin],
    upload.array("files",5),
    controller.upload
  );

If I change the upload.array("files",5) to upload.single("file") and change the front-end accordingly, it works by uploading one file.

I have no idea why upload.array() doesnt work.

1 Answer 1

2

The problem was that data.append("files", imageList); was essentially appending an array to an array, so the file array sent to the api was [[Files]], instead of a required [Files].

Changing it to

for (let i = 0; i < imageList.length; i++) {
  data.append("files", imageList[i]);
}

Fixed the problem.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.