MultipartFile 转 File 的两种方式

在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>
  • 6
    点赞
  • 57
    收藏
    觉得还不错? 一键收藏
  • 24
    评论
评论 24
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值