I need to send (upload) an image file from the web client (html+javascript) to the server (java/springboot) that will then store it.
On the client side I have created a form, of course
<form action="" name="missionForm" method="post" enctype="multipart/form-data" novalidate>
<fieldset>
<div class="field">
<label>
<span style="font-weight:bold">Mission name</span>
<input data-validate-length-range="3" name="name" id="name" required="required" />
</label>
</div>
<div class="field">
<label>
<span>Mission image (png):</span>
<input type='file' class='optional' name='loadImage' id='loadImage' accept='image/png'>
</label>
</div>
</fieldset>
</form>
The form is read below via javascript, who sends the request via fetch
document.forms[0].onsubmit = function(e){
e.preventDefault();
var imageFile = document.forms['missionForm']['loadImage'].files[0];
const test = fetch(url+"/api/saveImage", {
method: 'POST',
body: imageFile,
});
}
On the server side (Java / Springboot), I have created the following method in the Controller class
@PostMapping(value="/api/saveImage")
public void saveImage(@RequestParam("file") MultipartFile multipartFile) throws SQLException{
String fileName = StringUtils.cleanPath(multipartFile.getOriginalFilename());
System.out.println("filename is "+fileName);
}
When I launch this, I get error 500 on the client.
On the server side, I get the following error “org.springframework.web.multipart.MultipartException: Current request is not a multipart request”
I do not understand why. Can anybody help? I am sure I am missing something silly here.
Thanks!
I tried “forcing” the content-type in the fetch request, but I only get a different error
const test = fetch(url+"/api/saveImage", {
method: 'POST',
headers: {'Content-Type': 'multipart/form-data',},
body: imageFile,
});
and the error is “org.apache.tomcat.util.http.fileupload.FileUploadException: the request was rejected because no multipart boundary was found”