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 web project i'm getting uploaded file as Multipart file.I have to convert it to a File(io) ,there fore I can call this image storing service(Cloudinary).They only take type (File).
I have done so many searches but failed.If anybody knows a good standard way please let me know? Thnx
The answer by Alex78191 has worked for me.
For uploading files having size greater than 10240 bytes please change the maxInMemorySize in multipartResolver to 1MB.
small correction on @PetrosTsialiamanis post ,
new File( multipart.getOriginalFilename())
this will create file in server location where sometime you will face write permission issues for the user, its not always possible to give write permission to every user who perform action.System.getProperty("java.io.tmpdir")
will create temp directory where your file will be created properly. This way you are creating temp folder, where file gets created , later on you can delete file or temp folder.put this method in ur common utility and use it like for eg.
Utility.multipartToFile(...)
You can also use the Apache Commons IO library and the FileUtils class. In case you are using maven you can load it using the above dependency.
The source for the MultipartFile save to disk.
Although the accepted answer is correct but if you are just trying to upload your image to cloudinary, there's a better way:
Where multipartFile is your org.springframework.web.multipart.MultipartFile.
You can access tempfile in Spring by casting if the class of interface
MultipartFile
isCommonsMultipartFile
.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.