SpringMVC中MultipartFile转File的两种方式_java

2022年4月26日08:58:43

在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();//新文件名,时间戳形式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>
  • 作者:扯吧  
  • 原文链接:https://blog.csdn.net/qq_35564978/article/details/81701518
    更新时间:2022年4月26日08:58:43 ,共 1628 字。