Search code examples
javaspring-bootmultipartform-datafile-rename

Renaming the original file name of a Multipart file


I have this code where I wanted to rename the before saving it to the file system. I tried other questions here in stack overflow but it doesn't apply for me. Hoping you could help me this is my code.

@PostMapping("/api/file/upload")
public @ResponseBody String uploadMultipartFile(@RequestParam("uploadfile") MultipartFile file) {
        try {
            fileStorage.store(file);
            return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
        } catch (Exception e) {
            return "Error -> message = " + e.getMessage();
        }    
}

This is my store function:

@Override
public void store(MultipartFile file){
    try {
        Files.copy(file.getInputStream(), this.rootLocation.resolve(file.getOriginalFilename()));
    } catch (Exception e) {
        throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
    }
}

I tried renaming the original file but it doesn't work.

Hoping you could help me. Thank you so much!!!


Solution

  • Below is working snippet with little modification here and there :

    @PostMapping(value = "/api/file/upload", headers = {"content-type=multipart/*"})
    public @ResponseBody String uploadMultipartFile(@RequestParam("uploadfile") MultipartFile file) {
        Path TO = Paths.get("/Users/myusername/Desktop/newfileName");
        try {
            try {
                Files.copy(file.getInputStream(), TO);
            } catch (Exception e) {
                e.printStackTrace();
                throw new RuntimeException("FAIL2! -> message2 = " + e.getMessage());
            }
            return "File uploaded successfully! -> filename = " + file.getOriginalFilename();
        } catch (Exception e) {
            e.printStackTrace();
            return "Error -> message = " + e.getMessage();
        }
    }
    

    OutputScreen:

    enter image description here