I am using React in the frontend and Spring boot in the backend. I am trying to send a request that contains an image, as well as some json data by using the FormData in React.
This is my current code in the frontend:
const submitForm = (e: any) => {
e.preventDefault();
const swimArea = "{"swimArea" : {"name": "aTESTTEST", "longitude": "15.47", "latitude": "56.25"}}";
const formData = new FormData();
formData.append('swimArea', JSON.stringify(swimArea));
formData.append("file", e.target.file);
const requestOptions = {
method: "POST",
headers: {
"Content-Type": `multipart/form-data; boundary=----somefixedboundary`,
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "DELETE, POST, GET, OPTIONS",
"Access-Control-Allow-Headers": "Content-Type, Authorization, X-Requested-With",
},
body: formData,
};
fetch(
"http://localhost:8080/api/v1/bathplace/newBathingPlace",
requestOptions
)
.then((response) => response.json())
.then((data) => { // Continue with the data...
});
};
This is how the Spring API looks like:
@PostMapping(value = "/newBathingPlace")
public ResponseObject addBathingPlace(@RequestPart AddBathingPlaceRequest swimArea, @RequestPart MultipartFile file) {
// Handling the request...
return new ResponseObject();
}
I have tested the API with Postman and it works:
FormData in Postman
Request headers for the FormData in Postman
Now to the problem, in the browser I get this error:
"message": "Required request part ‘swimArea’ is not present"
I believe something is missing or wrong with the react-code, but not sure what. If you know anything please point me in the right direction.
I have tried removing the file-implementation from both server and client. Get the same error.
2
Answers
just change
formData.append("file", e.target.file);
toformData.append("file", e.currentTarget.files.[0])
I feel that the
FormData()
constructor is not used properly. You are stringifying the swimArea object twice. You have already stringified it when you created the object as, yet you are stringifying again at
formData.append('swimArea', JSON.stringify(swimArea));
You can try the following.
Also. when working with
FormData
, the browser automatically sets theContent-Type
tomultipart/form-data
with the correct boundary. Manually setting this header can cause issues.