Swaraj Pawar
Swaraj Pawar

Reputation: 43

unable to post with file upload using axios react js

I am trying to post multi-part form data with file upload using React and Axios. I tried the same in Postman and this is working correctly. But in react, I get "Required request part 'file' is not present". My code:

const selectedFile = event.target.file.files[0].name;

const formData = new FormData();
formData.append('name',this.state.name);
formData.append('description',this.state.description);
formData.append('file', selectedFile);
        
// Here I am passing content type and token and Post request . 
axios({
  method: 'post',
  url: 'http://localhost:8080/user/1/savecategory',
  data: formData,
  headers: {
    'Authorization':`Bearer ${passToken}`,
    'Content-Type':'multipart/form-data'
  }
})
.then(
  (response) => {
    alert("Category Saved..!");
  },
  (error) => {
    console.log(error);
    alert("Failed..!");
  }
);  

Upvotes: 1

Views: 2077

Answers (1)

Yves Kipondo
Yves Kipondo

Reputation: 5603

You haven't add the file field to the FormData Object. you only passed the name of the file as the second parameter.

de definition of append method is like this

For regular form field

formData.append(name, value);

And for Field field you can add It using this syntax

formData.append(name, value, filename);

Here selectedFile contain the name of the file which is selected in the file input field

const selectedFile = event.target.file.files[0].name;

When you call formData.append('file', selectedFile); you are passing the name of the file as value of the form element with name file and not the file It self.

to pass the file It self you should perform It like this

const selectedFile = event.target.file.files[0];

After that you can call formData.append('file', selectedFile);

Learn more about FormData.append

Upvotes: 3

Related Questions