I am trying to create a web form that will allow uploading a single file from the browser to my own server.
The backend API is spring boot based, the specific controller was tested with postman and worked well. Now when I am trying to make the same for my website using JavaScript and ajax I get the following error:
- Client side: Error 400 and
> {"status":"NOT_FOUND","message":"Current request is not a multipart > request","timestamp":1604939158692}
- server-side:
org.springframework.web.multipart.MultipartException: Current request is not a multipart request
I have tried ~10 of the accepted solutions from other question on stackoverflow, but nothing helped. These are the relevant code parts.
Spring controller:
@PostMapping("/add_users_from_csv")
public ResponseEntity<String> addUsersListFromCSVFile(@PathVariable String id, @RequestParam("file") MultipartFile file, @RequestParam("club") String clubId, @RequestParam("notifyByEmail") boolean notifyByEmail, @RequestParam("notifyBySMS") boolean notifyBySMS) throws UnauthorizedRequestException {
businessService.securityCheckID(id);
return clubService.addUsersListFromCSVFile(clubId, file, notifyByEmail, notifyBySMS);
}
Client:
<html>
<body>
<form name="uploadForm" id="fileUploadForm" method="POST" enctype="multipart/form-data">
<input type="file" id="file" name="file" value="Import"">
<input type="submit" value="Import" id="Import" />
</form>
<script type="text/javascript"
src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
$('form[name="uploadForm"]').submit(function(event){
event.preventDefault();
var formData = new FormData($('#fileUploadForm')[0]);
formData.append('file', $('input[type=file]')[0].files[0]);
formData.append("club", "5cc5fd05569a720006169111");
formData.append("notifyByEmail", "true");
formData.append("notifyBySMS", "true");
$.ajax({
url: 'http://localhost:8090/business/5cc625ed3ba686000665f111/add_users_from_csv',
data: formData,
type: "POST",
contentType: false,
processData: false,
cache: false,
"headers": {
"Content-Type": "application/json",
"Authorization": "bearer 0278e739-fbe0-4e3d-9acf-57544b011111"
},
success : function(response){
alert(response);
},
error: function(xhr,status,errorThrown) {
alert(xhr.status);
}
});
return false;
});
</script>
</body>
</html>
Postman request (that works well with the same server):
What makes the request from browser fail and how to fix it please ?