I have a REST API
for uploading files to server written in Java
with Spring Boot
. I am testing the API through postman. The API is working fine in Linux Environment, but in windows environment it returns 400 Bad Request
as response. There is no change in code in both systems, as I am using the same jar
file in both environments.
The POST
request consist of a file attachment in the form-data
and a parameter userName. My API accepts the data in that format only. I have checked the headers in the request in both the machines, and I am just passing a single header Content-Type
as application/json
.
Could someone guide me, what might be causing the error? I have checked some answers in stackoverflow for what might be the reasons for HTTP 400
other than the endpoint no being existing. Nothing answered my query.
Edit: Adding the code I am using to upload the file.
private static String UPLOADED_FOLDER_BIRTHDAY = "D:/uploads/birthday/";
@PostMapping("/api/upload/birthday")
public ResponseEntity<?> uploadFileForBirthday(@RequestParam("file") MultipartFile uploadfile, @RequestParam("userName") String userName) {
if (uploadfile.isEmpty()) {
return new ResponseEntity("please select a file!", HttpStatus.OK);
}
try {
saveUploadedFiles(Arrays.asList(uploadfile), UPLOADED_FOLDER_BIRTHDAY);
} catch (IOException e) {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
return new ResponseEntity("Successfully uploaded - " +
uploadfile.getOriginalFilename(), new HttpHeaders(), HttpStatus.OK);
}
private void saveUploadedFiles(List<MultipartFile> files, String uploadPath) throws IOException {
for (MultipartFile file : files) {
if (file.isEmpty()) {
continue;
}
byte[] bytes = file.getBytes();
Path path = Paths.get(uploadPath + file.getOriginalFilename());
Files.write(path, bytes);
}
}