如何将多部分文件转换为文件? [英] How to convert a multipart file to File?

查看:181
本文介绍了如何将多部分文件转换为文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以告诉我什么是将多部分文件(org.springframework.web.multipart.MultipartFile)转换为File(java.io.File)的最好方法吗?

在我的春天mvc web项目中,我得到上传文件为多部分文件。我必须将其转换为文件(io),因此我可以调用这个图像存储服务( Cloudinary )。他们只采取类型(文件)。

我做了这么多搜索,但失败。如果有人知道一个很好的标准方式,请让我知道?
Thnx

解决方案您可以获取 multipartFile 通过使用 getBytes 方法,您可以使用创建 File FileOutputStream 类。

  public文件转换(MultipartFile文件)
{
文件convFile =新文件(file.getOriginalFilename());
convFile.createNewFile();
FileOutputStream fos = new FileOutputStream(convFile);
fos.write(file.getBytes());
fos.close();
返回convFile;
}

您也可以使用transferTo方法

  public File multipartToFile(MultipartFile multipart)引发IllegalStateException,IOException 
{
文件convFile = new File(multipart.getOriginalFilename()) ;
multipart.transferTo(convFile);
返回convFile;
}


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

解决方案

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;
}

这篇关于如何将多部分文件转换为文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆