Search code examples
node.jsreactjsfile-uploadmulter

React NodeJS Multer file upload failure


Im trying to single file upload to folder public/files, using reactJS as frontend, multer nodeJS as serverside :

react :

here i have file input that accepts only pdf and msword, and on change it sets the file state, on submit it triggers function handleCareer which makes formData object and appends data from state, the file.name will be something like 1663010450031report.pdf, and then make request to /upload.

  const [file, setFile] = useState(null);

  const handleCareer = async () => {


    const data = new FormData();
    const pdf = `${Date.now()}${file.name}`;
    data.append("file", pdf);

    try {
      await fetch("http://localhost:8000/upload", {
        method: "POST",
        body: data,
      });
    } catch (err) {
      console.log(err);
    }
  };

      <div className="uploadCV">
        <label htmlFor="resumeFile" className="downloadImg">
          <AddAPhotoIcon className="postIcon" />
          <span>Upload resume</span>
        </label>

        <input
          type="file"
          accept="application/pdf,application/msword"
          id="resumeFile"
          name="file"
          onChange={(e) => setFile(e.target.files[0])}
        ></input>
      </div>

      <div className="submitUpload">
        <button type="button" onClick={handleCareer}>
          Request
        </button>
      </div>

server :

here im using path public/files as the target folder for upload and specifying in destination as well as specifying req.body.file for filename

app.use("/files", express.static(path.join(__dirname, "public/files")));

const storage = multer.diskStorage({
  destination: (req, file, cb) => {
    cb(null, "public/files");
  },
  filename: (req, file, cb) => {
    cb(null, req.body.file);
  },
});
const upload = multer({ storage: storage }).single("file");

app.post("/upload", function (req, res) {
  upload(req, res, function (err) {
    if (err instanceof multer.MulterError) {
      console.log(err);
    } else if (err) {
      console.log(err);
    }
    return res.status(200).send(req.file);
  });
});

but the file is not uploading, and it doesn't console log any errors, on postman it gives empty result with status code 200 .. what's is the problem here ?


Solution

  • You haven't send the file field to backend. You have to send a file (like pdf). Now you are sending only a pdf name. There aren't any file.

    const upload = multer({ storage: storage }).single("file");
    

    Here you have defined the name of incoming data is file. So you should add the field which named file