Java Convert MultipartFile to File for large files
11,114
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;
}
Comments
-
Abdennacer Lachiheb almost 2 years
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.
-
Abdennacer Lachiheb over 5 yearsit show this error cannot resolve method 'copy(java.io.InputStream, java.io.FileOutputStream) on this line Files.copy(...)
-
Abdennacer Lachiheb over 5 yearsThis method doesn't save the file I got FileNotFoundException
-
PowerStat over 5 yearsSorry then you have to add a create statement first.
-
Abdennacer Lachiheb over 5 yearswhat do you mean by create statement ?
-
Pavel Molchanov over 5 yearspublic File convert(MultipartFile file) throws IOException { File convFile = new File(file.getOriginalFilename()); convFile.createNewFile(); file.transferTo(convFile); return convFile; }
-
PowerStat over 5 yearsI checked the api and the createNewFile is not helpful. Looks like the point might be your environment - are you running with servlet 3.x api?
-
jannis over 5 yearsStream will not be closed in case of an exception. try-with-resources should be used here (
FileOutputStream fos = new FileOutputStream(convFile)
). -
jannis over 5 yearsI don't know where you took
Files.copy(InputStream, OutputStream)
from, but the input stream should probably be closed properly as well (but that depends on the library). -
jannis over 5 years@AbdenaceurLichiheb it's a mistake probably and the OP meant either
IOUtils#copy
from Apache Commons IO or Guava'sByteStreams#copy
. -
Firman Wijaya over 5 years@AbdenaceurLichiheb Updated my answer. @jannis
Files.copy(InputStream, OutputStream)
is actually a private method ofjava.nio.file.Files
class. My mistake -
Firman Wijaya over 5 years@AbdenaceurLichiheb
Files.readAllBytes()
reads all bytes into memory and potentially causes OOME. You should try to read from stream instead. -
jannis over 5 yearsYou have an error in
Files.copy(file.getInputStream(), convFile.toPath())
. Should beFiles.copy(is, convFile.toPath())
. Otherwise you open two streams and leave one hanging.