HPJM
HPJM

Reputation: 537

Problems uploading image file with multer (React and Node.js)

I've spent hours trying to find the solution for something which should be quite simple: uploading a file to the server from the client. I am using React.js on the frontend, Express on the backend, and multer for the image uploads.

When I try to upload a file, nothing happens. An uploads/ directory is created, but no file goes there. req.file and req.files are undefined. req.body.file is empty. The form data exists before it is sent.

If I set the Content-Type header to "multipart/form-data" I get a boundary error from multer.

Input

<input 
    onChange={this.sendFile}
    name="avatar"
    placeholder="Choose avatar"
    type="file"
/> 

sendFile

sendFile = e => {
    const data = new FormData();
    const file = e.target.files[0];
    data.append("file", file);
    this.props.sendFile(data);
};

Redux action

export default file => async dispatch => {
    const res = await axios.post("/api/upload/", { file });
};

Express

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

router.post("/upload/", upload.single("avatar"), (req, res) => {
    return res.sendStatus(200);
});

Upvotes: 0

Views: 4116

Answers (2)

Philipp Kief
Philipp Kief

Reputation: 8603

I tried to reproduce it and made it work with this method:

sendFile = e => {
  const data = new FormData();
  const file = e.target.files[0];
  data.append("avatar", file); // <-- use "avatar" instead of "file" here
  axios({
    method: 'post',
    url: 'http://localhost:9000/api/upload',
    data: data,
    config: { headers: { 'Content-Type': 'multipart/form-data' } }
  });
};

Upvotes: 4

lazreg87
lazreg87

Reputation: 953

Try to set the content-type header to multipart/form-data in the axios request and send the full FormData object as the second parameter.

Like this:

const config = {
    headers: {
        'content-type': 'multipart/form-data'
    }
};
axios.post('/api/upload/', file, headers);`

Upvotes: 1

Related Questions