trumanblack1025
trumanblack1025

Reputation: 491

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!!!

Upvotes: 1

Views: 5174

Answers (2)

greenhorn
greenhorn

Reputation: 654

Hope below code finds you well.

import java.nio.file.Path;

import java.nio.file.Files;

import org.springframework.web.multipart.MultipartFile;

 MultipartFile file;//file which you get from the API Request
 String newFileName = "new_file_name"
 String targetDir = "file_path"
 Path path = Paths.get(targetDir, newFileName);
 Files.copy(file.getInputStream(), path);

Upvotes: 0

Abhishek
Abhishek

Reputation: 1618

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

Upvotes: 1

Related Questions