0

Hi I try to add images to my server. So I made form in React and back-end post method. But my file.name is undefined and I cant add files to my server. For Image uplod I use react component from here : https://www.npmjs.com/package/react-images-upload

...
function handleSubmit(e) {
    e.preventDefault();
    const config = {
      headers: {
        'content-type': 'multipart/form-data',
      },
    };
    console.log(mainPicture);
    axios
      .post(
        prefix + '/api/add_project',
        {
          params: {
            name: name,
            description: description,
            address: address,
            used: used,
            about: about,
            mainPicture: mainPicture,
          },
        }
      )
      .then((response) => {
        alert('The file is successfully uploaded');
      })
      .catch((error) => { alert('failed')});
  }
....

<form onSubmit={handleSubmit}>
<label>
          Name:
          <input
            value={name}
            onChange={(e) => setName(e.target.value)}
            type="text"
            defaultValue="Name"
          />
        </label>
<ImageUploader
          name="mainPicture"
          {...props}
          buttonText="Choose Main Project Image"
          withIcon={true}
          withPreview={true}
          onChange={setMainPicture}
          imgExtension={['.jpg', '.gif', '.png', '.gif']}
          maxFileSize={5242880}
          singleImage={true}
        />
<button type="submit">Upload</button>
</form>

My Node.js backend

router.post('/api/add_project', (req, res, next) => {
  console.log("Request ---", req.body.params);
  console.log(JSON.stringify(req.body.params.mainPicture));
  if (Object.keys(req.body.params.mainPicture).length == 0) {
    return res.status(400).send('No files were uploaded.');
  }
  console.log(req.file);
  var file = req.file;
  console.log('file name: ' + file.name);
  if (
    file.mimetype == 'image/jpeg' ||
    file.mimetype == 'image/png' ||
    file.mimetype == 'image/gif'
  ) {
    file.mv('public/images/projects/' + file.name, function (err) {
      if (err) return res.status(500).send(err);
    });
  }
});

In my pm2 monit I can see that file is undefined: enter image description here Did I made mistake in front-end or in back-end? How should I solve this problem?

Emilis
  • 152
  • 1
  • 4
  • 21

1 Answers1

0

Make sure to pass content-type header and pass it as third parameter:

function postData() {
   const formData = new FormData();
   formData.append('file', fileData);
   formData.append('name', fileName);

    const config = {
      headers: {
       'content-type': 'multipart/form-data'
      }
    };

    axios.post('/upload', formData, config).then((response) => {
        console.log(response.data);
     }).catch((error) => {
        console.log(error);
     });
}
Lukas C
  • 393
  • 1
  • 2
  • 15