0

I am trying to upload a photo to mySQL database using a node backend but for some reason I am getting that what I have uploaded is undefined.

I have declared a new variable "Photo2" which is storing that photo and I console.log it but I get "undefined" in my console

The form:

import axios from "axios";
import { React, useState, useEffect } from "react";
import { useHistory, withRouter } from "react-router-dom";

function UserMaster_Edit(props) {
  const [CmpnyCode, setCmpnyCode] = useState("");
  const [UserID, setUserID] = useState("");
  const [UserFullName, setUserFullName] = useState("");
  const [UserDetail, setUserDetail] = useState("");
  const [LoginID, setLoginID] = useState("");
  const [Password, setPassword] = useState("");
  const [UserPin, setUserPin] = useState("");
  const [UserEmailID, setUserEmailID] = useState("");
  const [UserFP, setUserFP] = useState("");
  const [Photo, setPhoto] = useState("");
  const [IsActive, setIsActive] = useState("");
  const [LicCount, setLicCount] = useState("");
  const [DateCreated, setDateCreated] = useState("");
  const [CreatedBy, setCreatedBy] = useState("");
  const [RecordChanged, setRecordChanged] = useState("");
  const [LocationID, setLocationID] = useState("");
  const [isValid, setisValid] = useState("");
  const [isDeleted, setisDeleted] = useState("");

  const history = useHistory();

  const argu = props.match.params.UserID;

  useEffect(() => {
    axios.get("http://localhost:8000/getuserid/" + argu).then((response) => {
      setCmpnyCode(response.data[0].CmpnyCode);
      setUserID(response.data[0].UserID);
      setUserFullName(response.data[0].UserFullName);
      setUserDetail(response.data[0].UserDetail);
      setLoginID(response.data[0].LoginID);
      setPassword(response.data[0].Password);
      setUserPin(response.data[0].UserPin);
      setUserEmailID(response.data[0].UserEmailID);
      setUserFP(response.data[0].UserFP);
      setPhoto(response.data[0].Photo);
      setIsActive(response.data[0].IsActive.data[0]);
      setLicCount(response.data[0].LicCount);
      setDateCreated(response.data[0].DateCreated);
      setCreatedBy(response.data[0].CreatedBy);
      setRecordChanged(response.data[0].RecordChanged.data[0]);
      setLocationID(response.data[0].LocationID);
      setisValid(response.data[0].isValid);
      setisDeleted(response.data[0].isDeleted);
    });
  }, [argu]);

  const editData = () => {
    axios.put("http://localhost:8000/upusermst/" + argu, {
      CmpnyCode,
      UserID,
      UserFullName,
      UserDetail,
      LoginID,
      Password,
      UserPin,
      UserEmailID,
      UserFP,
      Photo,
      IsActive,
      LicCount,
      DateCreated,
      CreatedBy,
      RecordChanged,
      LocationID,
      isValid,
      isDeleted,
    });
    history.push("/usermst");
  };

  return (
    <div className="App">
      <div className="auth-wrapper">
        <div className="auth-inner">
          <form enctype="multipart/form-data" onSubmit={() => editData()}>
            <h3> Edit User Master</h3>
            <div>
              <div className="form-class8">
                <div className="form-group">
                  <label>Company Code</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="CompanyCode"
                    value={CmpnyCode}
                    onChange={(e) => {
                      setCmpnyCode(e.target.value);
                    }}
                    name="CmpnyCode"
                  />
                </div>

                <div className="form-group">
                  <label>UserID</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="UserID"
                    value={UserID}
                    onChange={(e) => {
                      setUserID(e.target.value);
                    }}
                    name="UserID"
                  />
                </div>

                <div className="form-group">
                  <label>UserFullName</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="UserFullName"
                    value={UserFullName}
                    onChange={(e) => {
                      setUserFullName(e.target.value);
                    }}
                    name="UserFullName"
                  />
                </div>

                <div className="form-group">
                  <label>UserDetail</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="UserDetail"
                    onChange={(e) => {
                      setUserDetail(e.target.value);
                    }}
                    name="UserDetail"
                    value={UserDetail}
                  />
                </div>

                <div className="form-group">
                  <label>LoginID</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="LoginID"
                    onChange={(e) => {
                      setLoginID(e.target.value);
                    }}
                    name="LoginID"
                    value={LoginID}
                  />
                </div>

                <div className="form-group">
                  <label>Password</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="Password"
                    onChange={(e) => {
                      setPassword(e.target.value);
                    }}
                    name="Password"
                    value={Password}
                  />
                </div>

                <div className="form-group">
                  <label>UserPin</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="UserPin"
                    onChange={(e) => {
                      setUserPin(e.target.value);
                    }}
                    name="UserPin"
                    value={UserPin}
                  />
                </div>

                <div className="form-group">
                  <label>UserEmailID</label>
                  <input
                    type="email"
                    className="form-control"
                    placeholder="UserEmailID"
                    onChange={(e) => {
                      setUserEmailID(e.target.value);
                    }}
                    name="UserEmailID"
                    value={UserEmailID}
                  />
                </div>
              </div>

              <div className="form-class8">
                <div className="form-group">
                  <label>UserFP</label>
                  <input
                    type="file"
                    className="form-control"
                    placeholder="UserFP"
                    onChange={(e) => {
                      setUserFP(e.target.value);
                    }}
                    name="UserFP"
                    value={UserFP}
                  />
                </div>

                <div className="form-group">
                  <label>Photo</label>
                  <input
                    type="file"
                    className="form-control"
                    placeholder="Photo"
                    onChange={(e) => {
                      setPhoto(e.target.value);
                    }}
                    name="Photo"
                    value={Photo}
                  />
                </div>

                <div className="form-group">
                  <label>IsActive</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="IsActive"
                    onChange={(e) => {
                      setIsActive(e.target.value);
                    }}
                    name="IsActive"
                    value={IsActive}
                  />
                </div>

                <div className="form-group">
                  <label>LicCount</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="LicCount"
                    onChange={(e) => {
                      setLicCount(e.target.value);
                    }}
                    name="LicCount"
                    value={LicCount}
                  />
                </div>

                <div className="form-group">
                  <label>DateCreated</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="DateCreated"
                    onChange={(e) => {
                      setDateCreated(e.target.value);
                    }}
                    name="DateCreated"
                    value={DateCreated}
                  />
                </div>

                <div className="form-group">
                  <label>CreatedBy</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="CreatedBy"
                    onChange={(e) => {
                      setCreatedBy(e.target.value);
                    }}
                    name="CreatedBy"
                    value={CreatedBy}
                  />
                </div>

                <div className="form-group">
                  <label>RecordChanged</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="RecordChanged"
                    onChange={(e) => {
                      setRecordChanged(e.target.value);
                    }}
                    name="RecordChanged"
                    value={RecordChanged}
                  />
                </div>

                <div className="form-group">
                  <label>LocationID</label>
                  <input
                    type="text"
                    className="form-control"
                    placeholder="LocationID"
                    onChange={(e) => {
                      setLocationID(e.target.value);
                    }}
                    name="LocationID"
                    value={LocationID}
                  />
                </div>
              </div>

              <div className="form-class8">
                <div className="form-group">
                  <label>isValid</label>
                  <input
                    type="date"
                    className="form-control"
                    placeholder="isValid"
                    onChange={(e) => {
                      setisValid(e.target.value);
                    }}
                    name="isValid"
                    value={isValid}
                  />
                </div>

                <div className="form-group">
                  <label>isDeleted</label>
                  <input
                    type="date"
                    className="form-control"
                    placeholder="isDeleted"
                    onChange={(e) => {
                      setisDeleted(e.target.value);
                    }}
                    name="isDeleted"
                    value={isDeleted}
                  />
                </div>
              </div>

              <button className="btn btn-primary btn-block">Edit</button>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
}

export default withRouter(UserMaster_Edit);

The fields that you are looking for are UserFP and Photo which are of type file.

Node backend:

const multer = require("multer");
const upload = multer({ storage: multer.memoryStorage() });


app.put("/upusermst/:UserID", upload.single("Photo"), (req, res) => {
  const userid = req.params.UserID;
  const CompanyCode = req.body.CmpnyCode;
  const UserID = req.body.UserID;
  const UserFullName = req.body.UserFullName;
  const UserDetail = req.body.UserDetail;
  const LoginID = req.body.LoginID;
  const Password = req.body.Password;
  const UserPin = req.body.UserPin;
  const UserEmailID = req.body.UserEmailID;
  const UserFP = req.body.UserFP;
  const Photo = req.body.Photo;
  const Photo2 = req.file;
  const IsActive = req.body.IsActive;
  const LicCount = req.body.LicCount;
  const DateCreated = req.body.DateCreated;
  const CreatedBy = req.body.CreatedBy;
  const RecordChanged = req.body.RecordChanged;
  const LocationID = req.body.LocationID;
  const isValid = req.body.isValid;
  const isDeleted = req.body.isDeleted;
  console.log(Photo2);
  db.query(
    "UPDATE usermst SET CmpnyCode=?,UserID=?,UserFullName=?,UserDetail=?,LoginID=?,Password=?,UserPin=?,UserEmailID=?,UserFP=?,Photo=?,IsActive=?,LicCount=?,DateCreated=?,CreatedBy=?,RecordChanged=?,LocationID=?,isValid=?,isDeleted=? WHERE UserID=?",
    [
      CompanyCode,
      UserID,
      UserFullName,
      UserDetail,
      LoginID,
      Password,
      UserPin,
      UserEmailID,
      UserFP,
      Photo,
      IsActive,
      LicCount,
      DateCreated,
      CreatedBy,
      RecordChanged,
      LocationID,
      isValid,
      isDeleted,
      userid,
    ],
    (err, result) => {
      if (err) {
        console.log(err);
      } else {
        res.send(result);
      }
    }
  );
});

Note that there is variable named Photo already but that was what I did before, now I am doing req.file for Photo2 and that is resulting to undefined.

I would really appreciate if someone can edit the code for me for better understanding with some explanation as to why I may be getting undefined for "Photo2"

2 Answers 2

2

After a lot of digging I finally figured out the problem. I had not installed jQuery hence the put request being sent by axios was giving the result undefined in the backend. I used fetch instead and it worked. The code is now as follows: The form:

const uploadPhoto = (event, argu) => {
    event.preventDefault();
    const formData = new FormData();
    formData.append("avatar", Photo);
    fetch("http://localhost:8000/uploadphoto/" + argu, {
      method: "PUT",
      body: formData,
    });
  };

 <form enctype="multipart/form-data">
             <div className="form-group">
                  <label>Photo</label>
                  <input
                    type="file"
                    className="form-control"
                    placeholder="Photo"
                    onChange={(e) => {
                      setPhoto(e.target.files[0]);
                    }}
                    id="Photo"
                    name="Photo"
                  />
</form>

Backend:

const multer = require("multer");
const fs = require("fs");

const upload = multer({ dest: "uploads/" });


app.put("/uploadphoto/:UserId", upload.single("avatar"), (req, res) => {
  const userid = req.params.userId;
  const photo = req.file;
  const fileType = photo.mimetype.split("/")[1];
  let newFileName = photo.filename + "." + fileType;

  fs.rename(
    `./uploads/${photo.filename}`,
    `./uploads/${newFileName}`,
    function () {
      console.log("file renamed and uploaded");
    }
  );
  console.log(photo);
  console.log("fileName ", newFileName);

  db.query(
    "UPDATE usermst SET Photo=? WHERE UserID=?",
    [newFileName, userid],
    (err, result) => {
      console.log(err);
      res.json({ result });
    }
  );
});```

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

Comments

0

Because file type inputs are not in e.target.value. The are in e.target.files. As you have only one image that would be e.target.files[0] in your case.

<input
  type="file"
  lassName="form-control"
  placeholder="Photo"
  onChange={(e) => {
    setPhoto(e.target.files[0]);
  }}
  name="Photo"
/>

By the way, you can't just send file along with request. You need to use formData instead.

Check out my minimal example:

import { useState } from "react";

export default function PrivatePage(props) {
  const [image, setImage] = useState(null);
  const [createObjectURL, setCreateObjectURL] = useState(null);

  const uploadToClient = (event) => {
    if (event.target.files && event.target.files[0]) {
      const i = event.target.files[0];

      setImage(i);
      setCreateObjectURL(URL.createObjectURL(i));
    }
  };

  const uploadToServer = async (event) => {
    const body = new FormData();
    body.append("file", image);
    const response = await fetch("/api/formidable", {
      method: "POST",
      body
    });
  };

  return (
    <div>
      <div>
        {createObjectURL&&<img height="500px" width="1000px" src={createObjectURL}/>}
        <h4>Select Image</h4>
        <input type="file" name="myImage" onChange={uploadToClient} />
        <button
          className="btn btn-primary"
          type="submit"
          onClick={uploadToServer}
        >
          Send to server
        </button>
      </div>
    </div>
  );
}

6 Comments

I have done that and now I am getting the following error in my console: react-dom.development.js:1383 Uncaught DOMException: Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename, which may only be programmatically set to the empty string. at HTMLInputElement.set [as value] And the whole interfact just goes blank, I can only see the background
No, I am using express
I have removed value ={photo} but I am still getting undefined in my backend console
This hasn't solved the issue. Still the same error I mentioned in the above comment The error is occuring at <input/> As soon as I select the image the error appears in the console and the interface goes blank
Yes please, That would be great
|

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.