springMVC文件上传

在web开发中一般会有文件上传的操作

一般JavaWeb开发中文件上传使用的 Apache组织的Commons FileUpload组件

SpringMVC中使用  MultipartFile file对象接受上传文件,必须保证 后台参数的名称和表单提交的文件的名称一致

文件上传必须条件

  1. 表单必须post
  2. 表单必须有 file 文件域
  3. 表单的 enctype="multipart/form-data"

 拷贝jar包

 

还有springmvc的jar包:

配置文件上传解析器:bean的名字是固定的

使用spring表达式 #{1024*1024}

<!-- 配置文件上传解析器:bean的名字是固定的,底层使用的名称注入 -->

<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">

    <!-- 设置上传文件的最大尺寸为1MB -->

    <property name="maxUploadSize" value="#{1024 * 1024}"></property>

</bean>

 主配置文件mvc.xml:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">
 3   <display-name>springMVC-demo910</display-name>
 4   <!-- 配置springMVC的前端控制器(总控) -->
 5   <servlet>
 6       <servlet-name>MVC</servlet-name>
 7       <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
 8       
 9       <init-param>
10           <param-name>contextConfigLocation</param-name>
11           <param-value>classpath:springmvc.xml</param-value>
12       
13       </init-param>
14       
15       <load-on-startup>1</load-on-startup>
16       
17   </servlet>
18   <servlet-mapping>
19       <servlet-name>MVC</servlet-name>
20       <url-pattern>*.do</url-pattern>
21   </servlet-mapping>
22   
23 </web-app>

springmvc配置文件:

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3     xmlns:p="http://www.springframework.org/schema/p"
 4     xmlns:context="http://www.springframework.org/schema/context"
 5     xmlns:aop="http://www.springframework.org/schema/aop"
 6     xmlns:tx="http://www.springframework.org/schema/tx"
 7     xmlns:mvc="http://www.springframework.org/schema/mvc"
 8     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 9     xsi:schemaLocation="
10         http://www.springframework.org/schema/beans
11         http://www.springframework.org/schema/beans/spring-beans.xsd
12         http://www.springframework.org/schema/context
13         http://www.springframework.org/schema/context/spring-context.xsd
14         http://www.springframework.org/schema/aop
15         http://www.springframework.org/schema/aop/spring-aop.xsd
16         http://www.springframework.org/schema/tx
17         http://www.springframework.org/schema/tx/spring-tx.xsd
18         http://www.springframework.org/schema/mvc
19         http://www.springframework.org/schema/mvc/spring-mvc.xsd">
20     
21     <!-- 配置组件扫描包的位置 -->
22     <context:component-scan base-package="top.abcdit.spring"/>
23     
24     <!-- 开启SpringMVC的注解驱动 -->
25     <mvc:annotation-driven/>
26     
27     
28     <!-- 配置文件上传解析器:bean的名字是固定的,底层使用的名称注入 -->
29      <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
30     <!-- 配置属性,文件大小,内存中最大能保存多少内容 -->
31     
32     <!-- 设置上传文件的最大尺寸为5MB 单位 字节 -->
33     <property name="maxUploadSize" value="#{1024 * 1024 * 5}"/>
34     
35 </bean>
36     
37     
38 </beans>

 文件上传表单:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
    <fieldset>
        <legend>单个文件上传</legend>  
        <!-- 
        enctype="application/x-www-form-urlencoded" 这里只是为字符进行编码,要改成enctype="multipart/form-data"
         -->
        <form action="${pageContext.request.contextPath}/upload.do" method="post" enctype="multipart/form-data">
            姓名:<input name="username"><br>
            头像:<input type="file" name="headImg"><span style="color: red;">${erroryMsg}</span><br>
            <button type="submit">提交</button>
        </form>
    </fieldset>
    
    <fieldset>
        <legend>多文件上传</legend>  
        <!-- 
        enctype="application/x-www-form-urlencoded" 这里只是为字符进行编码,要改成enctype="multipart/form-data"
         -->
        <form action="${pageContext.request.contextPath}/uploads.do" method="post" enctype="multipart/form-data">
            姓名:<input name="username"><br>
            文件1:<input type="file" name="headImgs"><br>
            文件2:<input type="file" name="headImgs"><br>
            文件3:<input type="file" name="headImgs"><span style="color: red;">${erroryMsg}</span><br>
            <button type="submit">提交</button>
        </form>
    </fieldset>
    
</body>
</html>

 控制器FileUploadController:

  1 package top.abcdit.spring.controller;
  2 
  3 import java.io.File;
  4 import java.io.IOException;
  5 import java.sql.Array;
  6 import java.util.Arrays;
  7 import java.util.List;
  8 import java.util.UUID;
  9 
 10 import org.apache.commons.io.FilenameUtils;
 11 import org.springframework.stereotype.Controller;
 12 import org.springframework.web.bind.annotation.ModelAttribute;
 13 import org.springframework.web.bind.annotation.RequestMapping;
 14 import org.springframework.web.bind.annotation.RequestParam;
 15 import org.springframework.web.multipart.MultipartFile;
 16 import org.springframework.web.servlet.ModelAndView;
 17 
 18 @Controller
 19 public class FileUploadController {
 20     /*
 21      * 如果是文件上传,后台使用 MultipartFile 来接受前台对应的文件 具体的文件接受使用的 Commons FileUpdate 组件 的实现类
 22      * org.springframework.web.multipart.commons.CommonsMultipartFile 来完成接受文件上传的
 23      * 注意:前台jsp页面文件域表单的名称必须和后台参数名称一致 <input type="file" name="headImg"><br>
 24      * MultipartFile headImg
 25      * 
 26      * 问题: 什么文件的MIME类型? 计算机上面所有的文件都有一个类型,这个类型叫做MIME类型 MIME类型的格式 xxx/xxx
 27      * tomcat/conf/web.xml有目前计算机上面所有数据类型的MIME的描述
 28      * 因为Tomcat要进行文件上传,要解析文件类型,所有在web.xml才有这些mieme的配置
 29      * 
 30      */
 31 
 32     @RequestMapping("/upload")
 33     public ModelAndView upload(@RequestParam String username, MultipartFile headImg) {
 34 
 35         System.out.println(username);
 36 
 37         String name = headImg.getName(); // 表单名称 <input type="file" name="headImg"><br>
 38         System.out.println(name);
 39 
 40         String filename = headImg.getOriginalFilename();
 41         System.out.println(filename);
 42 
 43         /*
 44          * String fileName = headImg.getOriginalFilename(); // 获取上传文件扩展名 String fileExt
 45          * = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()); //
 46          * 对扩展名进行小写转换 fileExt = fileExt.toLowerCase(); // 图片文件大小过滤
 47          * 
 48          * long fileSize = headImg.getSize(); if (fileSize>(1024*1025)) { ModelAndView
 49          * mvmax = new ModelAndView(); mvmax.addObject("erroryMax",
 50          * "您上传的图片大于1M,请上传1M以内的图片");
 51          * 
 52          * mvmax.setViewName("/request.jsp"); return mvmax; }
 53          */
 54 
 55         /*
 56          * 文件的MIME类型 判断文件是否是上传的类型
 57          * 
 58          *
 59          */
 60         String contentType = headImg.getContentType();
 61         System.out.println(contentType);
 62 
 63         // 允许文件上传的类型
 64         List<String> mimeTypes = Arrays.asList("image/jpeg", "image/png");
 65 
 66         if (!mimeTypes.contains(contentType)) {
 67             ModelAndView mv = new ModelAndView();
 68             mv.addObject("erroryMsg", "您上传的图片格式错误,请重新确认格式jpeg/jpg/png");
 69 
 70             mv.setViewName("/request.jsp");
 71 
 72             return mv;
 73         }
 74 
 75         File targetPath = new File("D:/imgFile");
 76 
 77         if (!targetPath.exists()) {
 78             targetPath.mkdir();
 79         }
 80 
 81         // 把用户上传的文件保存的服务器的某一个磁盘位置
 82         // 最终把文件名称保存到对应的数据库
 83 
 84         try {
 85             // 使用UUID生成新的随机文件名
 86             String uuid = UUID.randomUUID().toString().replaceAll("-", "");
 87             // 获取文件名后缀
 88             String extension = FilenameUtils.getExtension(filename);
 89 
 90             // 创建新的文件名称
 91             String newFileName = uuid + "." + extension;
 92 
 93             File dest = new File(targetPath, newFileName);
 94 
 95             // 保存文件
 96             headImg.transferTo(dest);
 97         } catch (Exception e) {
 98             e.printStackTrace();
 99         }
100 
101         return null;
102 
103     }
104     
105     @RequestMapping("/uploads")
106     public ModelAndView uploads(MultipartFile[] headImgs) {
107         
108         File targetPath = new File("d:/imgFile/MultipleImgFile");
109         
110         if (!targetPath.exists()) {
111             targetPath.mkdirs();
112         }
113         for (MultipartFile headImg : headImgs) {
114             //获取文件名称
115             String filename = headImg.getOriginalFilename();
116             
117             try {
118                 //使用UUID生成新的随机文件名
119                 String uuid = UUID.randomUUID().toString().replaceAll("-", "");
120                 
121                 //获取文件名后缀
122                 String extension = FilenameUtils.getExtension(filename);
123                 
124                 //创建新的文件名称
125                 String newFileName = uuid +"."+extension;
126                 File dest = new File("targetPath","newFileName");
127                 //保存文件    
128                 headImg.transferTo(dest);
129                 
130             } catch (Exception e) {
131                 e.printStackTrace();
132             }
133             
134         }
135         
136         return null;
137     }
138     
139     
140     
141     public static void main(String[] args) {
142         //commons-io 包中有一个工具类 FilenameUtils 专门对文件名称处理
143         
144         String filePath = "d:/imgFile/a/b/c/d/Doraemon3.jpg";
145         System.out.println(FilenameUtils.getBaseName(filePath)); //获取文件名Doraemon3
146         System.out.println(FilenameUtils.getName(filePath)); //获取文件名+后缀Doraemon3.jpg
147         System.out.println(FilenameUtils.getExtension(filePath));  //后缀jpg
148         
149         String uuid = UUID.randomUUID().toString();
150         String newFileName = uuid +"."+FilenameUtils.getExtension(filePath);
151         System.out.println(newFileName);
152         
153         String uuid2 = UUID.randomUUID().toString().replaceAll("-", "");  //强迫症患者可以去掉横杠“-”
154         String newFileName2 = uuid2 +"."+FilenameUtils.getExtension(filePath);
155         System.out.println(newFileName2);
156         
157     }
158 
159 }
原文地址:https://www.cnblogs.com/abcdjava/p/11172794.html