文件上传 SpringMvc

SpringMvc自带了文件上传功能,操作变得简化很多。此次试验应用的框架是Spring+SpringMvc+Mybatis

文件上传的重要节点在于:

后台获取到页面上传递过来的上传文件的信息,获取名称以及路径

数据库存储的信息其实是文件的路径

1.准备文件上传用到的jar包

    commons-fileupload-1.2.2.jar  commons-io-2.0.1.jar

2.在配置文件中添加支持

我用到的文件配置

    <!-- 文件上传解析器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
        p:maxUploadSize="34564356345456"  //最大上传尺寸
        p:defaultEncoding="utf-8">
        <!-- <property name="defaultEncoding" value="utf-8"></property> -->
    </bean>

借鉴的文件配置

<!-- SpringMVC上传文件时,需要配置MultipartResolver处理器 -->
    <bean id="multipartResolver"
        class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="defaultEncoding" value="UTF-8" />
        <!-- 指定所上传文件的总大小不能超过200KB。注意maxUploadSize属性的限制不是针对单个文件,而是所有文件的容量之和 -->
        <property name="maxUploadSize" value="-1" />
    </bean>

    <!-- SpringMVC在超出上传文件限制时,会抛出org.springframework.web.multipart.MaxUploadSizeExceededException -->
    <!-- 该异常是SpringMVC在检查上传的文件信息时抛出来的,而且此时还没有进入到Controller方法中 -->
    <bean id="exceptionResolver"
        class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="exceptionMappings">
            <props>
                <!-- 遇到MaxUploadSizeExceededException异常时,自动跳转到XXX页面 -->
                <prop
                    key="org.springframework.web.multipart.MaxUploadSizeExceededException">跳转XXX页面</prop>
            </props>
        </property>
    </bean>

 

3.上传jsp页面  enctype="multipart/form-data"必不可少

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>

  <h1>This is add.jsp</h1>
  <form action="<%=request.getContextPath()%>/shangchuan/add" method="post" enctype="multipart/form-data">
   姓名<input type="text" name="stuname" value="zhangsan"/>
   身份证号码<input type="text" name="idcard" value="11086"/>
   yourfile: <input type="file" name="myfile"/><br/>  
   yourfile: <input type="file" name="myfile"/><br/> 
   yourfile: <input type="file" name="myfile"/><br/> 
   <input type="submit" value="提交"/>
  
  </form>
</body>
</html>

4.后台controller接收页面

单独的文件上传,接收一个图片信息,将接收到到的信息保存在tomcat下面的文件夹

更改名称后的图片     c5109a80-52b0-4e1a-b2ce-05109c4b305b.jpg   
要保存的文件夹路径  /Users/wanghao/Desktop/work/apache-tomcat-8.5.9/wtpwebapps/wenjian/files   
图片路径的全称       /Users/wanghao/Desktop/work/apache-tomcat-8.5.9/wtpwebapps/wenjian/files/c5109a80-52b0-4e1a-b2ce-05109c4b305b.jpg

保存到数据库的字符串 files/c5109a80-52b0-4e1a-b2ce-05109c4b305b.jpg

 

    @RequestMapping(value="/add",method=RequestMethod.POST)
     public String add(Student student,MultipartFile myfile,HttpServletRequest request){
        
        if(myfile!=null){
       
        //获取文件名
            String filename=myfile.getOriginalFilename();
            String name=filename.substring(filename.length()-4, filename.length());
            //新的文件名
            String newfilename=UUID.randomUUID()+name;
            System.out.println(newfilename);
            //获取files文件夹的路径
            String path = request.getServletContext().getRealPath("files");
            System.out.println(path);
            path+="/"+newfilename;
            System.out.println(path);
            File file = new File(path);
             try {
                 // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
                 FileUtils.copyInputStreamToFile(myfile.getInputStream(), file);// 复制临时文件到指定目录下
             } catch (IOException e) {
                e.printStackTrace();
             }
     
        
         return "wenjian/list";
     }else{
         return null;
     }
    }

实现多个图片的上传@RequestParam 这个注解必须得有,MultipartFile[] 变成了数组的形式,循环便利接收到的图片信息,对每一张图片分别进行保存

@RequestMapping(value="/add",method=RequestMethod.POST)
     public String add(Student student,@RequestParam MultipartFile[] myfile,HttpServletRequest request){
        
        if(myfile!=null){
            for (int i = 0; i < myfile.length; i++) {
                
                //获取文件名
                   String filename=myfile[i].getOriginalFilename();
                   String name=filename.substring(filename.length()-4, filename.length());
                   //新的文件名
                   String newfilename=UUID.randomUUID()+name;
                   System.out.println(newfilename);
                    //获取files文件夹的路径
                   String path = request.getServletContext().getRealPath("files");
                    System.out.println(path);
                    path+="/"+newfilename;
                    System.out.println(path);
                    File file = new File(path);
                     try {
                        // FileUtils.copyInputStreamToFile()这个方法里对IO进行了自动操作,不需要额外的再去关闭IO流
                        FileUtils.copyInputStreamToFile(myfile[i].getInputStream(), file);// 复制临时文件到指定目录下
                    } catch (IOException e) {
                       e.printStackTrace();
                    }
             
                
            }
      
        
        
         return "wenjian/list";
     }else{
         return null;
     }

5.前台页面的效果图

文件上传 SpringMvc

6.保存的文件

文件上传 SpringMvc