I'm trying to change the name of MultipartFile.
I'm using MultipartFile on my controller to call rest service:
@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file)
{
...
}
Have you please any idea about changing the OriginalFilename of the uploaded file ?.
Big thanks.
You can try the following code.
@PostMapping("/post")
public ResponseEntity<String> handleFileUpload(@RequestParam("file") MultipartFile file)
{
try {
String filename = "random_filename.pdf"; // Give a random filename here.
byte[] bytes = file.getBytes();
String insPath = <DIRECTORY PATH> + filename // Directory path where you want to save ;
Files.write(Paths.get(insPath), bytes);
return ResponseEntity.ok(filename);
}
catch (IOException e) {
// Handle exception here
}
}
You have to remember to add a random string to the file name. If you just hard code the file name, every time you upload a file, the previous file will be replaced.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With