1

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..!");
  }
);  
1
  • The answer below is indeed correct. I would recommend not handling the upload yourself as there are edge-cases and cross-browser issues to handle that in Production code you'd want to cover. A library such as react-uploady takes care of all of that for you Commented Sep 19, 2020 at 10:56

1 Answer 1

4

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

Sign up to request clarification or add additional context in comments.

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.