Kumar Kelash
Kumar Kelash

Reputation: 23

How can I upload an image and form data as well on a single button click?

I am making a practice project in MERN stack and wanted to upload images from react js with the form on single button click, so I needed to call two apis on just one button click. But I am having errors that's why I am unable to upload image and form data as well.

My react js code here:

const URL = "http://localhost:2040/add_recipe";
      const formData = new FormData();

      formData.append("recipe_image", selectedFile);


let config = {
   headers: {
     "Content-Type": "multipart/form-data",
     authorization: JSON.parse(localStorage.getItem("token")),
    },
  };

axios
  .post(URL, formData, config)
  .then((response) => {
    console.log("Image uploaded successfully" + response);
  })
  .catch((error) => {
    console.log("Error while uploading image" + error);
  });

and here is my backend api:

const Recipe = require("../models/Recipe");
      const fs = require("fs");
      let filePath = "";



const AddRecipe = async (req, res) => {
   if (req.file) {
   filePath = req.file.path;
  }



console.log("filepath: " + filePath);


 let recipee = await Recipe.findOne({ name: req.body.name });
  if (recipee) {
   res.json({ Response: "Recipe already exists!" });
  }  else {
 if (
  req.body.category &&
  req.body.ptime &&
  req.body.name &&
  req.body.noOfPeople &&
  req.body.shortDesc &&
  req.body.recipe
 ) {
  let recipe = await Recipe.create({
    category: req.body.category,
    ptime: req.body.ptime,
    name: req.body.name,
    noOfPeople: req.body.noOfPeople,
    shortDesc: req.body.shortDesc,
    recipe: req.body.recipe,
    avatar: {
      data: fs.readFileSync(filePath),
      contentType: "image/png",
    },
    });


let result = await recipe;
    console.log(filePath + " .......path");
    if (result.name) {
    res.json({ Response: "Recipe added successfully!" });
    } else {
    res.json({ Response: "Recipe not added!" });
    }
    }
   }
  };

  module.exports = { AddRecipe };

This is how I called the api with multer already setup

app.post("/add_recipe", verifyToken, upload.single("recipe_image"), AddRecipe);

Upvotes: 0

Views: 1923

Answers (1)

Kumar Kelash
Kumar Kelash

Reputation: 23

I found the answer, actually I had to sent all data using FormData inside the axios request and its content-type would be multipart/form-data.

So, the request should be one because url is same and we can send form data and image as well using FormData append method and on backend we can get image as req.file and data as req.body.*

That's all!

Upvotes: 1

Related Questions