Home > Enterprise >  How to make a multipart request from node JS to spring boot?
How to make a multipart request from node JS to spring boot?

Time:05-23

I have a node js backend that needs to send a file to a spring boot application.

The file is local uploads/testsheet.xlsx.

Here is the code to upload the file using the form-data npm module and Axios.

const formData = new FormData()
formData.append("file", fs.createReadStream("uploads/testsheet.xlsx"));
formData.append("status", status);

const path = `/endpoint`
const auth = {
          username: username,
          password: password
}
const url = `${baseUrl}${path}`
const response = await sendRequest(url, auth, "POST", formData, null, null, null)


//sendRequest Code - 

 try {
const response = await axios({
  method,
  url,
  data,
  params,
  headers,
  auth,
  config,
})
return response
} catch (err) {
console.log(`Fetch Error: => ${method}:${url} => ${err.message || err.response}`)
return err.response ? { error: err.response.data.message } : { error: err.message }
}

The Spring boot side has the following code -

@PostMapping("/endpoint")
public StatusResponse update(@RequestParam("file") MultipartFile file, @RequestParam("status") String status){
    boolean response = transactionService.update(file, status);

    return statusResponse;
}

On the spring boot side, I keep getting this error -

  org.springframework.web.multipart.MultipartException: Current request is not a multipart request

While sending from the postman, everything works correctly.!!!

How do I send the multipart file successfully?

CodePudding user response:

You should use the .getHeaders() function that the formData object provides, in order to correctly set the multipart form boundary, e.g:

const res = await axios.post(url, formData, {
  headers: formData.getHeaders()
});
  • Related