[SOLVED] File upload in React and Node.js

Issue

This Content is from Stack Overflow. Question asked by John Oliver

I want to upload an image in the from React.js but it is not working.

The fileUploadHandler:

const uploadFileHandler = async (e) => {
    const file = e.target.files[0];
    let formData = new FormData();
    formData.append("image", file);
    setUploading(true);

    try {
      const config = {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      };
      const { data } = await axios.post(
        "http://localhost:5000/api/upload",
        formData,
        config
      );
      setImage(data);
      setUploading(false);
    } catch (error) {
      setUploading(false);
    }
  };

If I log the formData in the try block then it does not logs anything so is the data field and logs the error as below:
enter image description here

The multer configuration:

const storage = multer.diskStorage({
  destination(req, file, cb) {
    cb(null, "uploads/");
  },
  filename(req, file, cb) {
    cb(
      null,
      `${file.fieldname}-${Date.now()}${path.extname(file.originalname)}`
    );
  },
});

function checkFileType(file, cb) {
  const fileTypes = /jpg|jpeg|png/;
  const extName = fileTypes.test(path.extname(file.originalname).toLowerCase());
  const mimeType = fileTypes.test(file.mimeType);

  if (extName && mimeType) {
    return cb(null, true);
  } else {
    cb("Images Only!!");
  }
}

const upload = multer({
  storage,
  fileFilter: function (req, file, cb) {
    checkFileType(file, cb);
  },
});

router.post("/", upload.single("image"), (req, res) => {
  return res.send(`/${req.file.path}`);
});

The upload route in server.js file:
app.use("/api/upload", uploadRoutes);

Everything is fine in the backend but still getting the error.



Solution

I think the problem is your axios call :

try {
  let result = await axios.post(          // any call like get
    "http://localhost:3000/image",         // your URL
    {                                     // data if post, put
      data: data,
    },{
      headers:config,
    }
  );
  console.log(result.response.data);
} catch (error) {
  console.error(error.response.data);
}

try to call axios like this.


This Question was asked in StackOverflow by John Oliver and Answered by Mahmudul Hasan It is licensed under the terms of CC BY-SA 2.5. - CC BY-SA 3.0. - CC BY-SA 4.0.

people found this article helpful. What about you?