2
votes

I'm using nodejs, REACT, express, axios. I want to make upload function, but I can't. When I upload file, server cannot parse the uploaded file (only shows {} log).

Below is my frontend code

When user click UPLOAD button on form element, 'handleSubmit' function is called, and 'handleSubmit' calls 'fileUploadRequest' function.

In 'fileUploadRequest' function, everything is good. I can see infomations of attached file.

<form onSubmit={this.handleSubmit} encType='multipart/form-data'>
                    <input type="file" onChange={this.handleChange}/>
                    <input type="submit" value="UPLOAD"/>
</form>

export function fileUploadRequest(username, uploadFile, uploadFileName) {
    return (dispatch) => {
        dispatch(fileUpload());

        let formData = new FormData();
        formData.append('fileName', uploadFileName);
        formData.append('fileHandler', uploadFile);

        return axios.post('/upload/upload', {formData})
        .then((response) => {
            dispatch(fileUploadSuccess());
        }).catch((error) => {
            dispatch(fileUploadFailure());
        });
    };
}

below is backend code.

router.post('/upload', (req, res) => {

    console.log(req.body.);

    var form = new formidable.IncomingForm();
    form.parse(req, (err, fields, files) => {
        console.log('parse');
        console.log(fields);
        console.log(files);
    });
});

on req.body log, I can see only '{ formData: {} }' log.

'fields' and 'files' are all '{}' on log

How can I parse attached file on server?

2

2 Answers

2
votes

Use multer for Express to handle the uploaded file. Then use req.file to access all data about the uploaded file.

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

...

router.post('/upload', upload.single('fileHandler'), (req, res) => {
  console.log('req.file.filename', req.file.filename); // the filename will be generated by multer
  console.log('req.body.fileName', req.body.fileName); // to access the filename you created at the upload
});
0
votes

@kadiks, thank you. I can parse uploaded file with multer.

but I found something more problem. Even with multer, my code is not working.

below is not working code.

formData = new FormData();
formData.append('fileName', uploadFileName);
return axios.post('/upload/upload', {formData})

so i changed my code like this.

formData = new FormData();
formData.append('fileName', uploadFileName);
return axios.post('/upload/upload', formData);

only changed '{formData}' to 'formData', but this works good. I don't know why this happens. someone else know this reason, please comment this issue.