Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a multipart request from node js to spirng boot

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 form-data npm module and axios.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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 postman everything works correctly.!!!

How do I send the multipart file successfully?

>Solution :

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()
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading