javaspringspring-mvc

How to create MultipartFile with Spring 6.x.x without using MockMultipartFile


Up until Spring 5.x I was creating the multipart files that way (using now deprecated CommonsMultipartFile):

OutputStream outputStream;
final DiskFileItem diskFileItem = new DiskFileItem("file", mimeType, false, fileName, fileSize, repo));
try (InputStream inputStream = new FileInputStream(actualFile)) {
    outputStream = diskFileItem.getOutputStream();
    IOUtils.copy(inputStream, outputStream);
    return new CommonsMultipartFile(diskFileItem);
} catch (Exception e) {
    throw new GoogleConversionFailedException("Cannot build MultipartFile", e);
}

How to achieve the same result (create MultipartFile out of java.io.File) on Spring 6 without using MockMultipartFile (documentation states that it's supposed to be used for testing i really want to avoid that route)?


Solution

  • You could always just implement the interface which is straight-forward in your case:

    public class FileMultipartFile implements MultipartFile{
        private Path path;
        public FileMultipartFile(Path path){
            this.path=path;
        }
        @Override 
        public String getName(){
            return path.getFileName().toString();
        }
        @Override 
        public String getOriginalFilename() {
            return getName();
        }
        @Override
        public String getContentType() {
            try{
                 //not ideal as mentioned in the comments of https://stackoverflow.com/a/8973468/10871900 
                 return Files.probeContentType(path); 
            }catch(IOException e){
                 return null;
            }
        }
        @Override
        public long getSize() {
            return Files.size(path);
        }
        @Override
        public boolean isEmpty() {
            return getSize()==0;
        }
        @Override 
        public byte[] getBytes() throws IOException {
            return Files.readAllBytes(path);
        }
        @Override 
        public InputStream getInputStream() throws IOException {
             return Files.newInputStream(path);
        }
        @Override 
        public void transferTo(File dest) throws IOException, IllegalStateException {
            transferTo(dest.toPath());
        }
        @Override 
        public void transferTo(Path dest) throws IOException, IllegalStateException {
            Files.copy(path, dest);
        }
    }
    

    You can create instances using new FileMultipartFile(yourFile.toPath());

    In case you want to use a custom name, mime type or similar, you can add additional fields.