How to convert MultipartFile to java.io.File in Spring

25105


If you live in Spring world you might know that org.springframework.web.multipart.MultipartFile is the representation of an uploaded file received in a multipart request. But in some cases, you may want to convert this into java.io.File one such example can be what if you want to store the file into MongoDB? as MongoDB's APIs accepts java.io.File
With the following utility method, you can easily convert MultipartFile into Java File

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