How to convert a multi-page file to a file?

Can someone tell me what is the best way to convert a multi-page file (org.springframework.web.multipart.MultipartFile) to a file (java.io.File)?

In my spring mvc web project, I get the downloaded file as a Multipart file. I need to convert it to a file (io), so I can call this image storage service ( Cloudinary ). They accept only type (File).

I did so many searches, but could not. If anyone knows a good standard way, please let me know? Thnx

+75
java spring spring-mvc file-upload cloudinary
Jun 21 '14 at 8:55
source share
9 answers

You can get the contents of MultipartFile using the getBytes method, and you can write to a file using Files.newOutputStream() :

 public void write(MultipartFile file, Path dir) { Path filepath = Paths.get(dir.toString(), file.getOriginalFilename(); try (OutputStream os = Files.newOutputStream(filepath)) { os.write(file.getBytes()); } } 

You can also use the TransferTo method :

 public void multipartFileToFile( MultipartFile multipart, Path dir ) throws IOException { Path filepath = Paths.get(dir.toString(), multipart.getOriginalFilename()); multipart.transferTo(filepath); } 
+174
Jun 21 '14 at 9:03
source share

Although the accepted answer is correct, but if you are just trying to upload the image to the cloud, better:

 Map upload = cloudinary.uploader().upload(multipartFile.getBytes(), ObjectUtils.emptyMap()); 

Where multipartFile is your org.springframework.web.multipart.MultipartFile .

+14
Sep 19 '16 at 11:39
source share

a small correction for the post @PetrosTsialiamanis, new File( multipart.getOriginalFilename()) this will create a file in the server location, where sometime you will encounter write permission problems for the user, it can not always be granted write permission for each user, which performs the action. System.getProperty("java.io.tmpdir") will create a temporary directory where your file will be created correctly. This way you create a temporary folder in which the file is created, and then you can delete the folder with the files or temporary folders.

 public static File multipartToFile(MultipartFile multipart, String fileName) throws IllegalStateException, IOException { File convFile = new File(System.getProperty("java.io.tmpdir")+"/"+fileName); multipart.transferTo(convFile); return convFile; } 

put this method in a common ur utility and use it like for example. Utility.multipartToFile(...)

+9
Aug 17 '17 at 7:33
source share

You can also use the Apache Commons IO library and the FileUtils class . If you are using maven, you can download it using the above dependency.

 <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>2.4</version> </dependency> 

Source for saving MultipartFile to disk.

 File file = new File(directory, filename); // Create the file using the touch method of the FileUtils class. // FileUtils.touch(file); // Write bytes from the multipart file to disk. FileUtils.writeByteArrayToFile(file, multipartFile.getBytes()); 
+3
May 16 '16 at 16:48
source share

MultipartFile.transferTo (File) is good, but in the end, don't forget to clear the temporary file.

 // 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 on File.deleteOnExit (), executed when exiting the JVM (which can be extremely rare), details below.

+1
Feb 19 '19 at 9:20
source share

You can access the temporary file in Spring by casting if the MultipartFile interface class is equal to 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 smaller than 10,240 bytes, the maxInMemorySize property can be set to 0 in the @Configuration @EnableWebMvc class. After that, all downloaded files will be saved to disk.

 @Bean(name = "multipartResolver") public CommonsMultipartResolver createMultipartResolver() { CommonsMultipartResolver resolver = new CommonsMultipartResolver(); resolver.setDefaultEncoding("utf-8"); resolver.setMaxInMemorySize(0); return resolver; } 
0
Jul 09 '16 at 11:14
source share

The answer from Alex78191 worked for me.

 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 download files larger than 10,240 bytes, change maxInMemorySize in multipartResolver to 1 MB.

 <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- setting maximum upload size t 20MB --> <property name="maxUploadSize" value="20971520" /> <!-- max size of file in memory (in bytes) --> <property name="maxInMemorySize" value="1048576" /> <!-- 1MB --> </bean> 
0
Dec 29 '16 at 5:09
source share

if you do not want to use MultipartFile.transferTo (). You can write a file like this

  val dir = File(filePackagePath) if (!dir.exists()) dir.mkdirs() val file = File("$filePackagePath${multipartFile.originalFilename}").apply { createNewFile() } FileOutputStream(file).use { it.write(multipartFile.bytes) } 
0
Feb 26 '19 at 10:15
source share
  private File convertMultiPartToFile(MultipartFile file ) throws IOException { File convFile = new File( file.getOriginalFilename() ); FileOutputStream fos = new FileOutputStream( convFile ); fos.write( file.getBytes() ); fos.close(); return convFile; } 
-one
Nov 12 '18 at 11:24
source share



All Articles