Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a multipart file to File?

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

like image 613
Amila Iddamalgoda Avatar asked Jun 21 '14 08:06

Amila Iddamalgoda


People also ask

How do I convert a multipart file?

MultipartFile#getBytes We can use this method to write the bytes to a file: MultipartFile multipartFile = new MockMultipartFile("sourceFile. tmp", "Hello World". getBytes()); File file = new File("src/main/resources/targetFile.

What is a multipart file Java?

public interface MultipartFile extends InputStreamSource. A representation of an uploaded file received in a multipart request. The file contents are either stored in memory or temporarily on disk. In either case, the user is responsible for copying file contents to a session-level or persistent store as and if desired ...

What is a multi part file?

Multipart requests combine one or more sets of data into a single body, separated by boundaries. You typically use these requests for file uploads and for transferring data of several types in a single request (for example, a file along with a JSON object).


1 Answers

You can get the content of a MultipartFile by using the getBytes method and you can write to the 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); } 
like image 143
Petros Tsialiamanis Avatar answered Sep 29 '22 04:09

Petros Tsialiamanis