Current request is not a multipart request in spring boot and reactjs

When developing applications using Spring Boot as the backend and React.js for the frontend, you might come across scenarios where you need to handle multipart file uploads.

However, sometimes you may encounter an error message like “Current request is not a multipart request.” This issue typically arises due to a misconfiguration or a mismatch in how the frontend sends the request and how the backend expects it.

In this article, we’ll explore common reasons for encountering this error and provide solutions to resolve it.

Understand the Issue

The “Current request is not a multipart request” error occurs when Spring Boot @RequestParam or @RequestPart annotations for handling multipart requests do not receive a proper multipart request from the front end. This might happen if the Content-Type header or other request configurations are not set correctly.

Solutions

enctype Attribute in input form

When sending a file from a React.js frontend to a Spring Boot backend, ensure that the form containing the file input has the correct enctype attribute set to “multipart/form-data”. This tells the browser to send the form data as a multipart request.

Example:

<form encType="multipart/form-data" onSubmit={handleSubmit}>
  <input type="file" name="file" onChange={handleFileChange} />
  <button type="submit">Upload</button>
</form>

Verify your request configuration

when you using any HTTP client in React.js to make requests to your Spring Boot backend, ensure that the configuration is set to handle multipart data correctly.

Example:

headers: {
    'Content-Type': 'multipart/form-data'
  }

But you might face another error “the request was rejected because no multipart boundary was found” in your Spring boot console, Now let’s see how to solve this.

the request was rejected because no multipart boundary was found

To solve this Remove 'Content-Type': 'application/json' or 'Content-Type': 'multipart/form-data' from the header of your request that you are sending from reactJS.

Example:

if (token) {
    config = {
      'Authorization': 'Bearer ' + token,
    };
  } else {
    config = {
      'Content-Type': 'application/json'
    };
  }
  const response = await fetch(url, {
    method: method,
    headers: config,
    body: data
  });