开始需要在pom.xml加入几个jar,分别是

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

接下来,在Springmvc的配置加入上传文件的配置(PS:我把springmvc的完整配置都展现出来):

  1. <!--默认的mvc注解映射的支持 -->
  2. <mvc:annotation-driven/>
  3. <!-- 处理对静态资源的请求 -->
  4. <mvc:resources location="/static/" mapping="/static/**" />
  5. <!-- 扫描注解 -->
  6. <context:component-scan base-package="com.ztz.springmvc.controller"/>
  7. <!-- 视图解析器 -->
  8. <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  9. <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
  10. <!-- 前缀 -->
  11. <property name="prefix" value="/WEB-INF/jsp/"/>
  12. <!-- 后缀 -->
  13. <property name="suffix" value=".jsp"/>
  14. </bean>
  15. <!-- 上传文件 -->
  16. <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
  17. <property name="defaultEncoding" value="utf-8"/>
  18. <!-- 最大内存大小 -->
  19. <property name="maxInMemorySize" value=""/>
  20. <!-- 最大文件大小,-1为不限制大小 -->
  21. <property name="maxUploadSize" value="-1"/>
  22. </bean>

一、 单文件上传

当然在一个表单中,需要添加enctype="multipart/form-data",一个表单有文件域,肯定也有基本的文本框,可以一次性提交,springmvc能给我们区别出来,来做不同的处理。首先看下普通的model

  1. package com.ztz.springmvc.model;
  2.  
  3. public class Users {
  4. private String name;
  5. private String password;
  6. //省略get set方法
  7.  
  8. //重写toString()方便测试
  9. @Override
  10. public String toString() {
  11. return "Users [name=" + name + ", password=" + password + "]";
  12. }
  13. }

这个是表单的JSP页面:

  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
  2. <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6. request.setAttribute("basePath", basePath);
  7. %>
  8. <!DOCTYPE html>
  9. <html>
  10. <head>
  11. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  12. <title>FileUpload</title>
  13. </head>
  14. <body>
  15. <form action="${basePath}file/upload" method="post" enctype="multipart/form-data">
  16. <label>用户名:</label><input type="text" name="name"/><br/>
  17. <label>密&nbsp;码:</label><input type="password" name="password"/><br/>
  18. <label>头&nbsp;像</label><input type="file" name="file"/><br/>
  19. <input type="submit" value="提 交"/>
  20. </form>
  21. </body>
  22. </html>

上传成功跳转的JSP页面,并且显示出上传图片:

  1. <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
  2. <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
  3. <%
  4. String path = request.getContextPath();
  5. String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
  6. request.setAttribute("basePath", basePath);
  7. %>
  8. <!DOCTYPE html>
  9. <html>
  10. <head>
  11. <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  12. <title>头像</title>
  13. </head>
  14. <body>
  15. <img src="${basePath}${imagesPath}">
  16. </body>
  17. </html>

最后是Controller:

  1. package com.ztz.springmvc.controller;
  2.  
  3. import java.io.File;
  4. import java.util.UUID;
  5.  
  6. import javax.servlet.http.HttpServletRequest;
  7.  
  8. import org.springframework.stereotype.Controller;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11. import org.springframework.web.bind.annotation.RequestParam;
  12. import org.springframework.web.multipart.MultipartFile;
  13.  
  14. import com.ztz.springmvc.model.Users;
  15.  
  16. @Controller
  17. @RequestMapping("/file")
  18. public class FileUploadController {
  19.  
  20. @RequestMapping(value="/upload",method=RequestMethod.POST)
  21. private String fildUpload(Users users ,@RequestParam(value="file",required=false) MultipartFile file,
  22. HttpServletRequest request)throws Exception{
  23. //基本表单
  24. System.out.println(users.toString());
  25.  
  26. //获得物理路径webapp所在路径
  27. String pathRoot = request.getSession().getServletContext().getRealPath("");
  28. String path="";
  29. if(!file.isEmpty()){
  30. //生成uuid作为文件名称
  31. String uuid = UUID.randomUUID().toString().replaceAll("-","");
  32. //获得文件类型(可以判断如果不是图片,禁止上传)
  33. String contentType=file.getContentType();
  34. //获得文件后缀名称
  35. String imageName=contentType.substring(contentType.indexOf("/")+);
  36. path="/static/images/"+uuid+"."+imageName;
  37. file.transferTo(new File(pathRoot+path));
  38. }
  39. System.out.println(path);
  40. request.setAttribute("imagesPath", path);
  41. return "success";
  42. }
  43. //因为我的JSP在WEB-INF目录下面,浏览器无法直接访问
  44. @RequestMapping(value="/forward")
  45. private String forward(){
  46. return "index";
  47. }
  48. }

点击提交控制台输出:

Users [name=fileupload, password=test]

二、 多图片上传

springmvc实现多图片上传也很简单,我们把刚才的例子修改下,在加一个文件域,name的值还是相同

  1. <body>
  2. <form action="${basePath}file/upload" method="post" enctype="multipart/form-data">
  3. <label>用户名:</label><input type="text" name="name"/><br/>
  4. <label>密&nbsp;码:</label><input type="password" name="password"/><br/>
  5. <label>头&nbsp;像1</label><input type="file" name="file"/><br/>
  6. <label>头&nbsp;像2</label><input type="file" name="file"/><br/>
  7. <input type="submit" value="提 交"/>
  8. </form>
  9. </body>

展示图片来个循环,以便显示多张图片

  1. <body>
  2. <c:forEach items="${imagesPathList}" var="image">
  3. <img src="${basePath}${image}"><br/>
  4. </c:forEach>
  5. </body>

控制层代码如下:

  1. package com.ztz.springmvc.controller;
  2.  
  3. import java.io.File;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.util.UUID;
  7.  
  8. import javax.servlet.http.HttpServletRequest;
  9.  
  10. import org.springframework.stereotype.Controller;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestMethod;
  13. import org.springframework.web.bind.annotation.RequestParam;
  14. import org.springframework.web.multipart.MultipartFile;
  15.  
  16. import com.ztz.springmvc.model.Users;
  17.  
  18. @Controller
  19. @RequestMapping("/file")
  20. public class FileUploadController {
  21.  
  22. @RequestMapping(value="/upload",method=RequestMethod.POST)
  23. private String fildUpload(Users users ,@RequestParam(value="file",required=false) MultipartFile[] file,
  24. HttpServletRequest request)throws Exception{
  25. //基本表单
  26. System.out.println(users.toString());
  27.  
  28. //获得物理路径webapp所在路径
  29. String pathRoot = request.getSession().getServletContext().getRealPath("");
  30. String path="";
  31. List<String> listImagePath=new ArrayList<String>();
  32. for (MultipartFile mf : file) {
  33. if(!mf.isEmpty()){
  34. //生成uuid作为文件名称
  35. String uuid = UUID.randomUUID().toString().replaceAll("-","");
  36. //获得文件类型(可以判断如果不是图片,禁止上传)
  37. String contentType=mf.getContentType();
  38. //获得文件后缀名称
  39. String imageName=contentType.substring(contentType.indexOf("/")+);
  40. path="/static/images/"+uuid+"."+imageName;
  41. mf.transferTo(new File(pathRoot+path));
  42. listImagePath.add(path);
  43. }
  44. }
  45. System.out.println(path);
  46. request.setAttribute("imagesPathList", listImagePath);
  47. return "success";
  48. }
  49. //因为我的JSP在WEB-INF目录下面,浏览器无法直接访问
  50. @RequestMapping(value="/forward")
  51. private String forward(){
  52. return "index";
  53. }
  54. }

Spring4 MVC 多文件上传(图片并展示)的更多相关文章

  1. MVC图片上传、浏览、删除 ASP.NET MVC之文件上传【一】(八) ASP.NET MVC 图片上传到服务器

    MVC图片上传.浏览.删除   1.存储配置信息 在web.config中,添加配置信息节点 <appSettings> <add key="UploadPath" ...

  2. MVC之文件上传1

    MVC之文件上传 前言 这一节我们来讲讲在MVC中如何进行文件的上传,我们逐步深入,一起来看看. Upload File(一) 我们在默认创建的项目中的Home控制器下添加如下: public Act ...

  3. Spring MVC的文件上传和下载

    简介: Spring MVC为文件上传提供了直接的支持,这种支持使用即插即用的MultipartResolver实现的.Spring MVC 使用Apache Commons FileUpload技术 ...

  4. 0062 Spring MVC的文件上传与下载--MultipartFile--ResponseEntity

    文件上传功能在网页中见的太多了,比如上传照片作为头像.上传Excel文档导入数据等 先写个上传文件的html <!DOCTYPE html> <html> <head&g ...

  5. Spring MVC实现文件上传

    基础准备: Spring MVC为文件上传提供了直接支持,这种支持来自于MultipartResolver.Spring使用Jakarta Commons FileUpload技术实现了一个Multi ...

  6. Asp.net mvc 大文件上传 断点续传

    Asp.net mvc 大文件上传 断点续传 进度条   概述 项目中需要一个上传200M-500M的文件大小的功能,需要断点续传.上传性能稳定.突破asp.net上传限制.一开始看到51CTO上的这 ...

  7. Spring MVC的文件上传

    1.文件上传 文件上传是项目开发中常用的功能.为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data.只有在这种情况下,浏览器才会把用户 ...

  8. 整合MVC实现文件上传

    1.整合MVC实现文件上传整合MVC实现文件上传在实际的开发中在实现文件上传的同时肯定还有其他信息需要保存到数据库,文件上传完毕之后需要将提交的基本信息插入数据库,那么我们来实现这个操作.整个MVC实 ...

  9. 【Spring学习笔记-MVC-13】Spring MVC之文件上传

    作者:ssslinppp       1. 摘要 Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的.Spring使用Jakarta Co ...

随机推荐

  1. ZOJ 3594 年份水题 【注意:没有0年】

    #include<iostream> #include<cstdio> #include<cstring> #include<algorithm> #i ...

  2. Android 如何引用com.android.internal.R目录下的资源

    Android 如何引用com.android.internal.R目录下的资源 项目需求 有一个资源跟系统上的一个资源相同,想要引用它:frameworks/base/core/res/res/dr ...

  3. Android layoutInflate.inflate 方法具体解释,removeView()错误解决

    错误: The specified child already has a parent. You must call removeView(). 解答: 这个错误非常直白,就是你viewGroup. ...

  4. MSSQL - 尚未备份数据库 xxxx 的日志尾部。如果该日志包含您不希望丢失的工作,请使用 BACKUP LOG WITH NORECOVERY 备份该日志。请使用 RESTORE 语句的 WITH REPLA

    此错误的原因是:你的数据库服务器中存在同名数据库! RESTORE DATABASE  [student] FROM  DISK = N'G:\备份文件'  WITH  FILE = 1, MOVE ...

  5. Qt中Ui名字空间以及setupUi函数的原理和实现

    用最新的QtCreator选择GUI的应用会产生含有如下文件的工程 下面就简单分析下各部分的功能. .pro文件是供qmake使用的文件,不是本文的重点[不过其实也很简单的],在此不多赘述. 所以呢, ...

  6. Node.js and Forever “exited with code: 0”

    CentOs 6.5 using root acount, I have a working Node.js Express app: root@vps [/home/test/node]# npm ...

  7. 免插件打造wordpress投稿页面

    一.新建投稿页面模板 把主题的 page.php 另存为 tougao.php,并且在第一行的 <?php 之后添加模板的标识注释: /* Template Name: tougao */ 紧接 ...

  8. 事务管理在三层架构中应用以及使用ThreadLocal再次重构

    本篇将详细讲解如何正确地在实际开发中编写事务处理操作,以及在事务处理的过程中使用ThreadLocal的方法. 在前面两篇博客中已经详细地介绍和学习了DbUtils这个Apache的工具类,那么在本篇 ...

  9. Mongodb 上传图片

    mongdb 上传图片: [root@hy-mrz01 ~]# mongofiles put -u "pics" -p "jh7yxx" --host 127. ...

  10. [置顶] ArcGIS发布最新的 ArcGIS Runtime SDK for Android v10.1.1

    因为希望有统一的地图解决方案,就是PC端,移动端的数据一致,看到ArcGIS的最新发布,感兴趣的可以围观. 链接:http://blogs.esri.com/esri/arcgis/2013/09/0 ...