Java Convert MultipartFile to File for large files

Abdennacer Lachiheb :

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;
}

Wich work's fine but for large files I got this exception :

java.lang.OutOfMemoryError: Java heap space

I added more heap but 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.

Firman Wijaya :

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;
  }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=83839&siteId=1