I'm trying to implement this Spring endpoint:
private static String UPLOADED_FOLDER = "/opt/";
@PostMapping(value = "/upload", produces = { MediaType.APPLICATION_JSON_VALUE })
public ResponseEntity<StringResponseDTO> uploadFile(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes, @RequestParam("id") Integer merchant_id) throws Exception {
InputStream inputStream = file.getInputStream();
try {
byte[] bytes = file.getBytes();
File directory = new File(UPLOADED_FOLDER, merchant_id.toString());
directory.mkdirs();
File newFile = new File(directory, file.getOriginalFilename());
newFile.renameTo(new File("merchant_logo.png"));
Files.write(newFile.toPath(), bytes);
redirectAttributes.addFlashAttribute("message",
"You successfully uploaded '" + file.getOriginalFilename() + "'");
} catch (IOException e) {
e.printStackTrace();
}
return ResponseEntity.ok(new StringResponseDTO(originalName));
}
The general idea is to rename the file and override previous file with the same name. But for some reason it's not working. I get the old file content. Any idea why?