skip to Main Content

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


  1. just change formData.append("file", e.target.file); to formData.append("file", e.currentTarget.files.[0])

    Login or Signup to reply.
  2. 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

    const swimArea = "{"swimArea" : {"name": "aTESTTEST", "longitude":
    "15.47","latitude": "56.25"}}";
    

    , yet you are stringifying again at

    formData.append('swimArea', JSON.stringify(swimArea));

    You can try the following.

    const submitForm = (e) => {
        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.files[0])
    
       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...
          });
    };
    

    Also. when working with FormData, the browser automatically sets the Content-Type to multipart/form-data with the correct boundary. Manually setting this header can cause issues.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search