Search code examples
javaspringmultipart

Java Convert MultipartFile to File for large files


I'm using the below method to convert MultipartFile to a File:

public File convert(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        convFile.createNewFile();
        FileOutputStream fos = new FileOutputStream(convFile);
        fos.write(file.getBytes());
        fos.close();
        return convFile;
}

Which works fine but for large files I got this exception:

java.lang.OutOfMemoryError: Java heap space

I added more heap, but I'm still having the error.

So is there a programmatic way to fix this maybe splitting the multipart file to smaller chunks while converting, but I'm not sure how to code it.

Any help or suggestion would be greatly appreciated.


Solution

  • Does MultipartFile belong to Spring's package org.springframework.web.multipart? If so, you could do

      public File convert(MultipartFile file) throws IOException {
        File convFile = new File(file.getOriginalFilename());
        convFile.createNewFile();
          try(InputStream is = file.getInputStream()) {
            Files.copy(is, convFile.toPath()); 
          }
        return convFile;
      }