在spring上传文件中,一般都使用了MultipartFile来接收,但是有需要用到File的地方,这里只介绍两种转为File的方法,当然也有一些其他的方法,我试了有些错误,所以就不提了;
- transferTo()
- org.apache.commons.io.FileUtils.copyInputStreamToFile()
代码如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
|
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(); //新文件名,时间戳形式yyyyMMddHHmmssSSS String saveFileName = fileNewName.concat(fileSuffix); //新文件完整名(含后缀) String filePath = "D:\\FileAll" ; File path = new File(filePath); //判断文件路径下的文件夹是否存在,不存在则创建 if (!path.exists()) { path.mkdirs(); } File savedFile = new File(filePath); boolean isCreateSuccess = savedFile.createNewFile(); // 是否创建文件成功 if (isCreateSuccess){ //将文件写入 //第一种 file.transferTo(savedFile); //第二种 savedFile = new File(filePath,saveFileName); // 使用下面的jar包 FileUtils.copyInputStreamToFile(file.getInputStream(),savedFile); } } catch (Exception e) { e.printStackTrace(); } } else { System.out.println( "文件是空的" ); } } |
附commons-io jar包maven地址:点击下载 commons-io-2.4.jar
1
2
3
4
5
6
|
<!-- https://mvnrepository.com/artifact/commons-io/commons-io --> < dependency > < groupId >commons-io</ groupId > < artifactId >commons-io</ artifactId > < version >2.4</ version > </ dependency > |
到此这篇关于SpringMVC中MultipartFile转File的两种方式的文章就介绍到这了,更多相关SpringMVC MultipartFile转File内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://blog.csdn.net/qq_35564978/article/details/81701518