0

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);
});

2 Answers 2

4

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' } }
  });
};
Sign up to request clarification or add additional context in comments.

1 Comment

Great! It worked for me. Even for a array consisting of images, it got uploaded.
1

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);`

Comments

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.