java 将File文件转换成 MultipartFile 文件问题
一、首先将File文件转换成FileItem文件
1,引入相关jar, pom中加入commons-fileupload依赖架包
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.4</version>
</dependency>
2,转换方法实现
/**
* 将file 文件转换成FileItem 文件 便于转换成 MultipartFile 文件
* @version 2021-1-2810:43:18
* @author zhouzj
* @param file
* @param fileName
* @return
*/
public static FileItem createFileItem(File file, String fileName)
{
String filePath = file.getPath();
FileItemFactory factory = new DiskFileItemFactory(16, null);
String textFieldName = "file";//切忌,这个必须与 MultipartFile 传输的 是一致的 如feign 调用 @RequestPart("file") MultipartFile file
int num = filePath.lastIndexOf(".");
String extFile = filePath.substring(num);
FileItem item = factory.createItem(textFieldName, "multipart/form-data", true,
fileName);
int bytesRead = 0;
byte[] buffer = new byte[8192];
try
{
FileInputStream fis = new FileInputStream(file);
OutputStream os = item.getOutputStream();
while ((bytesRead = fis.read(buffer, 0, 8192))
!= -1)
{
os.write(buffer, 0, bytesRead);
}
os.close();
fis.close();
}
catch (IOException e)
{
e.printStackTrace();
}
return item;
}
二、将FileItem文件转换成MultipartFile文件
FileItem fileItem = BaseUtil.createFileItem(file, fileName);
MultipartFile multipartFile = new CommonsMultipartFile(fileItem);