Can any one tell me what is a the best way to convert a multipart file (org.springframework.web.multipart.MultipartFile) to File (java.io.File) ?
In my spring mvc w
You can access tempfile in Spring by casting if the class of interface MultipartFile
is CommonsMultipartFile
.
public File getTempFile(MultipartFile multipartFile)
{
CommonsMultipartFile commonsMultipartFile = (CommonsMultipartFile) multipartFile;
FileItem fileItem = commonsMultipartFile.getFileItem();
DiskFileItem diskFileItem = (DiskFileItem) fileItem;
String absPath = diskFileItem.getStoreLocation().getAbsolutePath();
File file = new File(absPath);
//trick to implicitly save on disk small files (<10240 bytes by default)
if (!file.exists()) {
file.createNewFile();
multipartFile.transferTo(file);
}
return file;
}
To get rid of the trick with files less than 10240 bytes maxInMemorySize
property can be set to 0 in @Configuration
@EnableWebMvc
class. After that, all uploaded files will be stored on disk.
@Bean(name = "multipartResolver")
public CommonsMultipartResolver createMultipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setDefaultEncoding("utf-8");
resolver.setMaxInMemorySize(0);
return resolver;
}
MultipartFile.transferTo(File) is nice, but don't forget to clean the temp file after all.
// ask JVM to ask operating system to create temp file
File tempFile = File.createTempFile(TEMP_FILE_PREFIX, TEMP_FILE_POSTFIX);
// ask JVM to delete it upon JVM exit if you forgot / can't delete due exception
tempFile.deleteOnExit();
// transfer MultipartFile to File
multipartFile.transferTo(tempFile);
// do business logic here
result = businessLogic(tempFile);
// tidy up
tempFile.delete();
Check out Razzlero's comment about File.deleteOnExit() executed upon JVM exit (which may be extremely rare) details below.
Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:
Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap());
Where multipartFile is your org.springframework.web.multipart.MultipartFile.