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
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.
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 ...
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).
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); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With