MultipartFile 转 File 的两种方式

  • Post author:
  • Post category:其他


在spring上传文件中,一般都使用了MultipartFile来接收,但是有需要用到File的地方,这里只介绍两种转为File的方法,当然也有一些其他的方法,我试了有些错误,所以就不提了;

  1. transferTo()
  2. 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();//新文件名,时间戳形式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

<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
		<groupId>commons-io</groupId>
		<artifactId>commons-io</artifactId>
		<version>2.4</version>
</dependency>



版权声明:本文为qq_35564978原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。