File sent from react not showing up in backend response body

Viewed 128

I'm trying to get a file from the user in my react application and then send that file to my back end and upload it to s3 bucket. I am successfully able to choose a file and it even shows up in the console. But when I send it to the back end, it just shows empty braces.

Here's the code to update the state:

handleInputChange = (event) => {
        this.setState({
            ...this.state,
            file: event.target.files[0]
        })
    }

This is the code to send the file

  submit = () => {
        console.log(this.state.file)
        axios.post(process.env.REACT_APP_SERVER + '/uploadThumbnail', { file: this.state.file, status: true})
            .then(response => {
                console.log(response)
            })
    }

Now, I can see the file in console. But in backend, it shows

REQUEST BODY: {file:{}, status: false}

Anyone knows how to solve this issue?

1 Answers

It's not right to send the file as a json. I guess you are using nodejs backend and maybe using multer for file upload?

To send a file object via api, you have to send it as a form data.

const data = new FormData();
data.append('file', this.state.file);
data.append('status', true);
axios.post(process.env.REACT_APP_SERVER + '/uploadThumbnail', data, {
    headers: {
        'Content-Type': 'multipart/form-data'
    }
})
.then(response => {
    console.log(response)
})
Related