SpringMVC实现 MultipartFile 文件上传

1. Maven 工程引入所需要的依赖包

2. 页面需要开放多媒体标签

3. 配置文件上传试图解析器

4. 接收图片信息,通过 IO 流写入磁盘(调用解析其中的方法即可)

如下:

  1.1 引入所依赖的jar包

 1 <dependency>
 2   <groupId>commons-io</groupId>
 3   <artifactId>commons-io</artifactId>
 4   <version>2.4</version>
 5 </dependency>
 6 <dependency>
 7   <groupId>commons-fileupload</groupId>
 8   <artifactId>commons-fileupload</artifactId>
 9   <version>1.3.1</version>
10 </dependency>

  2.1 页面需要开放多媒体标签

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
    <h2>上传多个文件 实例</h2>  
    <form action="/upload/filesUpload" method="post"  enctype="multipart/form-data">  
        <p>选择文件:<input type="file" name="files"></p>
        <p>选择文件:<input type="file" name="files"></p>
        <p><input type="submit" value="提交"></p>
    </form>  
</body>
</html>

  3.1 配置文件上传试图解析器

 <!-- 多部分文件上传 -->
    <!--id的名字只能为multipartResolver-->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">  
        <!--配置编码格式-->
        <property name="defaultEncoding" value="utf-8"></property>   
         <!--配置文件上传大小-->
        <property name="maxUploadSize" value="10485760000"></property>  
        <property name="maxInMemorySize" value="40960"></property>  
   </bean> 

  4.1 编写controller,实现文件上传

@Controller
public class FileController {

    //实现了文件上传入门案例
    @RequestMapping("/file")
    //MultipartFile    解析器参数
    public String file(MultipartFile fileImage) throws IllegalStateException, IOException{
        /*
         * 公共接口MultipartFile 
            扩展了InputStreamSource
            在多部分请求中接收的上载文件的表示。
            文件内容存储在内存中或临时存储在磁盘上。
            在任何一种情况下,如果需要,用户负责将文件内容复制到会话级或持久性存储。
            临时存储将在请求处理结束时清除。
         */
        
        //创建fileDir对象,"E:/jt-upload"这个内容可以是文件也可以是文件夹
        File fileDir = new File("E:/jt-upload");
        //1.判断文件夹是否存在
        if(!fileDir.exists()){
            //不存在的话,创建文件夹
            fileDir.mkdirs();
        }
        
        //fileImage.getOriginalFilename()    获取文件名字
        String fileName = fileImage.getOriginalFilename();
        
        //实现文件的上传
        fileImage.transferTo(new File("E:/jt-upload/"+fileName));
        
        //适用重定向技术
        return "redirect;/file.jsp";
        //z转发
//        return "forword:/file.jsp";
    }
    
}
原文地址:https://www.cnblogs.com/gxlaqj/p/9931333.html