项目上为了方便测试会将CommonsMultipartFile转File,我们可以利用CommonsMultipartFile类中的getInputStream()方法获得文件流然后转换成File
public InputStream getInputStream() throws IOException {
if (!isAvailable()) {
throw new IllegalStateException("File has been moved - cannot be read again");
}
InputStream inputStream = this.fileItem.getInputStream();
return (inputStream != null ? inputStream : StreamUtils.emptyInput());
}
具体实现如下
先获取CommonsMultipartFile类型的文件
commonsMultipartFile = (CommonsMultipartFile) multipartHttpServletRequest.getFile("file");
File backFile = new File("随机文件的路径");
try {
backFile.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
try {
//调用InputStream转File的inputSteamToFile方法
inputSteamToFile(commonsMultipartFile.getInputStream(),backFile);
} catch (IOException e) {
e.printStackTrace();
}
InputStream转File的inputSteamToFile方法
private static void inputSteamToFile(InputStream ins, File file){
FileOutputStream os = null;
try {
os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[1024];
while ((bytesRead = ins.read(buffer)) != -1){
os.write(buffer,0,bytesRead);
}
}catch (Exception e){
e.printStackTrace();
}finally {
try {
if (os != null){
os.close();
}
if (ins != null){
os.close();
}
}catch (IOException e){
e.printStackTrace();
}
}
}
完成后已将CommonsMultipartFile类型的文件转为File类型