Amila Iddamalgoda Amila Iddamalgoda - 6 months ago 1282
Java Question

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

Answer

You can get the content of multipartFile by using getBytes and you can create a File by using FileOutputStream.

public File convert(MultipartFile file)
{    
    File convFile = new File(file.getOriginalFilename());
    convFile.createNewFile(); 
    FileOutputStream fos = new FileOutputStream(convFile); 
    fos.write(file.getBytes());
    fos.close(); 
    return convFile;
}

You can also use the method transferTo

public File multipartToFile(MultipartFile multipart) throws IllegalStateException, IOException 
{
        File convFile = new File( multipart.getOriginalFilename());
        multipart.transferTo(convFile);
        return convFile;
}