Skip to content
Advertisement

react + spring boot upload file and form data

i have a case like in my form (front end), i can fill personal data (name, address, DOB) and then i can attach multiple image.

In my spring boot controller :

JavaScript

My model wrapper :

JavaScript

Front end (React) Code :

JavaScript

With above example, i always encounter errors. like : java.io.IOException: Stream closed and zero attachment length / zero attachment size (have switch from array of MultipartFile or List of MultipartFile). please throw some light for this case, as a lot of tutorial out there only for upload the attachment part, not including the form data that user has filled. Thanks before.

tutorial reference : SO MK

Updated front end code :

JavaScript

changed the front end code using formdata then got error in backend :

JavaScript

Advertisement

Answer

Edited

First Exception Solution

You are consuming multipart/form-data in your server-side, so you must send data as formData.

Use const formData = new FormData(form); instead of JSON.stringify


Second Exception Solution

Your second exception is for the binding error, you’re trying to bind String into Multipart, it is because of this line

JavaScript

1- You can set an onChange in the form for file, like onFileChangeHandler

JavaScript

2- Set uploaded file in formData and send it (like below code)

Body of onChange can be as follows

JavaScript

below link might be useful for your case:

File Upload with React Js (Axios) and Spring REST

Advertisement