How to convert a multipart file to File?

2019-01-10 05:08发布

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

7条回答
趁早两清
2楼-- · 2019-01-10 05:59

You can get the content of multipartFile by using the getBytes method and you can create an instance of the File class by using the FileOutputStream class.

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 transferTo method:

public File multipartToFile(MultipartFile multipart) throws IllegalStateException, IOException 
{
    File convFile = new File( multipart.getOriginalFilename());
    multipart.transferTo(convFile);
    return convFile;
}
查看更多
登录 后发表回答