Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change the name of MultipartFile

Tags:

spring-boot

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.

like image 990
OraBo Avatar asked Sep 07 '25 01:09

OraBo


1 Answers

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.

like image 124
Johna Avatar answered Sep 10 '25 04:09

Johna