Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

file upload using axios in react

I am uploading a file in React using Axios. When I am doing

alert(values.attachedFile[0]);, it displays:

"localhost:4200 says [Object object]"

but when I am sending values.attachedFile[0] in an Axios post request, an empty object is being sent.

const { result } = await axios.post(app.resourceServerUrl + '/file/upload', {
    data: values.attachedFile[0],
    headers: {
        'Content-Type': 'multipart/form-data',
    },
});

You can see the request data being empty:

enter image description here

What is my mistake?

like image 679
Shruti sharma Avatar asked Jun 13 '26 01:06

Shruti sharma


1 Answers

To upload file with axios you need to use FormData:

const formData = new FormData();

// ...

formData.append("data", values.attachedFile[0]);
axios.post(app.resourceServerUrl + '/file/upload', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})
like image 144
Fiodorov Andrei Avatar answered Jun 15 '26 16:06

Fiodorov Andrei



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!