在spring上传文件中,一般都使用了MultipartFile来接收,但是有需要用到File的地方,这里只介绍两种转为File的方法,当然也有一些其他的方法,我试了有些错误,所以就不提了;
- transferTo()
- org.apache.commons.io.FileUtils.copyInputStreamToFile()
代码如下:
public void upload(@RequestParam(value = "file") MultipartFile file) {
if (file != null) {
try {
String fileRealName = file.getOriginalFilename();//获得原始文件名;
int pointIndex = fileRealName.lastIndexOf(".");//点号的位置
String fileSuffix = fileRealName.substring(pointIndex);//截取文件后缀
String fileNewName = DateUtils.getNowTimeForUpload();//文件new名称时间戳
String saveFileName = fileNewName.concat(fileSuffix);//文件存取名
String filePath = "D:\\FileAll" ;
File savedFile = new File(filePath);
if(!savedFile.exists()){
savedFile.mkdirs();
}
savedFile = new File(filePath,saveFileName);
boolean isCreateSuccess = savedFile.createNewFile();
if(isCreateSuccess){ //转存文件
file.transferTo(savedFile); //第一种
FileUtils.copyInputStreamToFile(mufile.getInputStream(),savedFile); //第二种
}
} catch (Exception e) {
e.printStackTrace();
}
}else {
System.out.println("文件是空的");
}
}
附commons.io jar包maven地址:
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>