1:MultipartFile 转成File
public static File multipartFileToFile(MultipartFile file ) {
File toFile = null;
try{
if(file==null||file.equals("")||file.getSize()<=0){
file = null;
}else {
InputStream ins = file.getInputStream(); //获取MultipartFile的输入流
String filePath = file.getOriginalFilename();
filePath = filePath.substring(filePath.lastIndexOf("/")+1);
toFile = new File(filePath); //根据老文件名创建一个File对象
OutputStream os = new FileOutputStream(file);//根据File创建一个输出流
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead); //将输入流写到输出流中
}
ins.close();
os.close();
}
}catch(Exception e){
//这里进行异常处理
}
return toFile;
}
理解:首先以MultipartFile的名字创建一个File对象,然后以MultipartFile为输入流的源头,以新File对象为输出流的目的地,最后进行流的读写即可。
2:File 转成 MultipartFile
(1):
public static MultipartFile fileToMultipartFile( File file ) {
FileInputStream fileInput = new FileInputStream(file);
MultipartFile toMultipartFile = new MockMultipartFile("file",file.getName(),"text/plain", IOUtils.toByteArray(fileInput));
return toMultipartFile;
}
理解:以File为输入流的源头,然后将其转成字节数组,最终以字节数组创建MultipartFile。
(2):
public static MultipartFile fileToMultipartFile( File file ) {
FileItem fileItem = createFileItem(file); //根据File创建FileItem
MultipartFile mfile = new CommonsMultipartFile(fileItem);//根据FileItem创建MultipartFile
return mfile;
}
private static FileItem createFileItem(File file){
FileItemFactory factory = (FileItemFactory) new DiskFileItemFactory();
String textFieldName = "textField";
int num = file.getName().lastIndexOf(".");
String extFile = file.getName().substring(num);
FileItem item = factory.createItem(textFieldName, "text/plain", true,"MyFileName" + extFile);//根据File名创建一个FileItem
int bytesRead = 0;
byte[] buffer = new byte[8192];
try {
FileInputStream fis = new FileInputStream(file); //以File为源头创建输入流
OutputStream os = item.getOutputStream(); //以FileItem为目的地创建输出流
while ((bytesRead = fis.read(buffer, 0, 8192)) != -1){
os.write(buffer, 0, bytesRead); //将输入流写入输出流
}
os.close();
fis.close();
}catch (IOException e){
//异常处理
}
return item;
}
理解:将File转换成FileItem,最后以FileItem创建MultipartFile