Search code examples
javascriptreactjsexpressmerncloudinary

How to upload Image to Cloudinary - MERN Stack


I want to add some company details to mongo DB, and the details include a company logo. So I want to upload the picture to Cloudinary and then save the URL in Mongo DB with the other details.

But my code doesn't seem to work. When I fill the form and click on submit, the image gets uploaded to Cloudinary but it does not get saved in the Database.

To store the image

const [ companyLogo, setCompanyLogo] = useState("");
const [ companyLogoURL, setCompanyLogoURL] = useState("");

Function to execute on submit

const handleCompanySubmit = (evt) => {
    evt.preventDefault();

    const data = new FormData()
    data.append("file", companyLogo)
    data.append("upload_preset", "Sprint")
    data.append("cloud_name", "sprint-ccp")
    fetch("https://api.cloudinary.com/v1_1/sprint-ccp/image/upload",{
      method:"post",
      body:data
    })
    .then(res => res.json())
    .then(data => {
      setCompanyLogoURL(data.url)
    })
    .catch(err => {
      console.log(err)
    })

    //check for empty fields
    if (
      isEmpty(companyName) ||
      isEmpty(companyAddress) ||
      isEmpty(companyRegNumber) ||
      isEmpty(companyContactNumber)
    ) {
      setCompanyErrorMsg("Please Fill All The Fields");
    }else {
      let formData = new FormData();
      formData.append('companyName', companyName);
      formData.append('companyAddress', companyAddress);
      formData.append('companyRegNumber', companyRegNumber);
      formData.append('companyContactNumber', companyContactNumber);
      formData.append('companyLogo', companyLogoURL);

      setCompanyLoading(true);

      addCompany(formData)
      .then((response) => {
        setCompanyLoading(false);
          setCompanySuccessMsg(response.data.successMsg)
          setCompanyData({
            companyName: "",
            companyAddress: "",
            companyRegNumber: "",
            companyContactNumber: ""
          });
      })
      .catch((err) => {
        setCompanyLoading(false);
        setCompanyErrorMsg(err.response.data.errorMsg)
      })
    }
  };

const handleCompanyLogo = (evt) => {
    setCompanyLogo(evt.target.files[0])
  };

frontend view

<form className="register-form" onSubmit={handleCompanySubmit} noValidate>

     <label className="text-secondary">Company Logo :</label>
     <input type="file"  className="form-control" onChange={handleCompanyLogo}/>

     //remaining input fields

     <button className="btn btn-info submitButton" >Submit</button>
                  
</form>
    
    

api for adding company

export const addCompany = async (data) => {
    const config = {
      headers: {
        "Content-Type": "application/json",
      },
    };
  
    const response = await axios.post(
      "http://localhost:5000/api/auth/clients/company",
      data,
      config
    );
  
    return response;
  };

controller in backend

exports.addNewCompany = async(req,res)=>{

  const { 
    companyName,
    companyAddress,
    companyRegNumber,
    companyContactNumber,
    companyLogo
  } = req.body;

  const company = await Company.findOne({ companyName });
    if (company) {
      return res.status(400).json({
        errorMsg: `${req.body.companyName} already exists`,
      });
    }

  try{
    const newCompany = new Company();
    newCompany.companyName = companyName;
    newCompany.companyAddress = companyAddress;
    newCompany.companyRegNumber = companyRegNumber;
    newCompany.companyContactNumber = companyContactNumber;
    newCompany.companyLogo = companyLogo;

    await newCompany.save();
    res.json({
      successMsg: `${req.body.companyName} Company Added Successfully`
    });
  } catch (err) {
    console.log("clientsController error - Add Company ", err);
    res.status(500).json({
      errorMsg: "Server Error. Please Try again",
    });
  }
};

The error i get in the console is this

clientsController error - Add Company Error: Company validation failed: companyLogo: Path companyLogo is required. at ValidationError.inspect

(C:\CCP\sd08_2021\Backend\node_modules\mongoose\lib\error\validation.js:47:26)

Can you please help me out ?


Solution

  • I think that your error is caused by a more trivial problem :

    When you send the POST request with fetch, you don't actually wait for its completion (it's a promise), so the code in the if ... else {...} statement is executed before the termination of the fetch() !

    setCompanyLogoURL(data.url) has not been called yet, so formData.append('companyLogo', companyLogoURL); set a blank string instead of the value returned by the call to the Cloudinary API.

    The solution would be to make handleCompanySubmit async, and to await for the fetch() promise completion.