How to change originalFilename of MultipartFile

Viewed 12530

I have a MultipartFile file on server side. I would like to change the original file name of this file, yet the class only support getOriginalFilename().

Can anyone help me with this? PS: It is an image file uploaded.

Thanks alot.

3 Answers

Just create a new MultipartFile instance by updating its

originalFileName

with new one other files with the same existing file fields.

Just call following method as

getNewFile("newFileName", currentFile)

current file is the MultipartFile object of the existing file.

private MultipartFile getNewFile(String fileName, MultipartFile currentFile){
        return new MultipartFile() {
            @Override
            public String getName() {
                return currentFile.getName();
            }

            @Override
            public String getOriginalFilename() {
                return fileName;
            }

            @Override
            public String getContentType() {
                return currentFile.getContentType();
            }

            @Override
            public boolean isEmpty() {
                return currentFile.isEmpty();
            }

            @Override
            public long getSize() {
                return currentFile.getSize();
            }

            @Override
            public byte[] getBytes() throws IOException {
                return currentFile.getBytes();
            }

            @Override
            public InputStream getInputStream() throws IOException {
                return currentFile.getInputStream();
            }

            @Override
            public void transferTo(File file) throws IOException, IllegalStateException {

            }
        };
    }
public String storeFile(MultipartFile file) {
        String fileName = StringUtils.cleanPath(file.getOriginalFilename());
//this will provide the complete filename, let "file.txt";
        File fileSaved = fileRepository.save(new File());
//let's save that on a repo, not file, just some reference, easy to handle
        fileName = fileName.substring(0, fileName.length() - 4) + fileSaved.getFileId() + fileName.substring(fileName.length() - 4);
//change the file name a bit, just put the id from the repo, it will be unique by default, right ? and what's that 4 - ".txt" has 4 alphabets, currently i neeed to handle only txt, so I hard-coded this
        Path targetLocation = this.fileStorageLocation.resolve(fileName);
        Files.copy(file.getInputStream(), targetLocation, StandardCopyOption.REPLACE_EXISTING);
//it will be never replaced, even filenames are same,id will be unique
}
Related