实现上传图片功能在Springmvc中很好实现。现在我将会展现完整例子。

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

  1. <dependency>
  2. <groupId>commons-fileupload</groupId>
  3. <artifactId>commons-fileupload</artifactId>
  4. <version>1.3.1</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="10240"/>
  20. <!-- 最大文件大小,-1为不限制大小 -->
  21. <property name="maxUploadSize" value="-1"/>
  22. </bean>

一、 单文件上传

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

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

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

点击提交控制台输出:

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

PS:本demo地址:http://download.csdn.net/detail/zwz568017880/9043089

springmvc上传图片并显示图片--支持多图片上传的更多相关文章

  1. Jquery图片上传组件,支持多文件上传

    Jquery图片上传组件,支持多文件上传http://www.jq22.com/jquery-info230jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消. ...

  2. ajax 提交所有表单内容及上传图片(文件),以及单独上传某个图片(文件)

    我以演示上传图片为例子: java代码如下(前端童鞋可以直接跳过看下面的html及js): package com.vatuu.web.action; import java.io.File; imp ...

  3. PHP 图片上传工具类(支持多文件上传)

    ====================ImageUploadTool======================== <?php class ImageUploadTool { private ...

  4. php 图片上传 并返回上传文件位置 支持多文件上传

    <?php /** * Created by PhpStorm. * User: DY040 * Date: 2018/4/26 * Time: 13:23 */ echo '<pre&g ...

  5. 适应各浏览器图片裁剪无刷新上传jQuery插件(转)

    看到一篇兼容性很强的图片无刷新裁剪上传的帖子,感觉很棒.分享下!~ 废话不多说,上效果图. 一.首先建立如下的一个page <!DOCTYPE html> <html xmlns=& ...

  6. puzz: 图片和表单上传的不一致问题

    1.    方向1 用户提交表单, 图片和表单同步上传.(由同一服务器处理, 服务器压力大. 没有分离) 2.    方向2 图片和表单分开上传. 如图片访问ftp,表单提交后台(图片和后台分离) 2 ...

  7. 移动前端—H5实现图片先压缩再上传

    在做移动端图片上传的时候,用户传的都是手机本地图片,而本地图片一般都相对比较大,拿iphone6来说,平时拍很多图片都是一两M的,如果直接这样上传,那图片就太大了,如果用户用的是移动流量,完全把图片上 ...

  8. 使用html5 FileReader获取图片,并异步上传到服务器(不使用iframe)

    使用html5 FileReader获取图片,并异步上传到服务器(不使用iframe)   原理: 1.使用FileReader 读取图片的base64编码 2.使用ajax,把图片的base64编码 ...

  9. #添加图片,最多只能上传9张.md

    #添加图片,最多只能上传9张.md 前端页面: ```javascript <form id="imgForm" enctype="multipart/form-d ...

  10. 使用html5 FileReader获取图片,并异步上传到server(不使用iframe)

    使用html5 FileReader获取图片,并异步上传到server(不使用iframe) 原理: 1.使用FileReader 读取图片的base64编码 2.使用ajax.把图片的base64编 ...

随机推荐

  1. window对象的inner/outer/page/screen详解

    innerHeight : 返回窗口的文档显示区的高度,包含工具条与滚动条.说明:ie8以下不支持 outerHeight : 返回窗口的外部高度,包含工具条与滚动条.说明:ie8以下不支持 page ...

  2. php配置rewrite模块

    转 (1)    启用rewrite模块,在默认情况下,没有启用 修改httpd.conf文件 #启动rewrite模块 LoadModule rewrite_module modules/mod_r ...

  3. php正则表达式治疗结巴

    用正则表达式去解决结巴这个问题可以通过下面进行解决: 解决思路是: 先找到重复的不部分 用str_replace($source,$replace,$str);来进行代理 下面分两种情况,最后将这两种 ...

  4. workqueue机制分析之process_one_work分析

    工作者线程不断执行,从work_poll结构中卸下一个work, 然后进入函数process_one_work 来执行这个work. process_one_work(struct worker *w ...

  5. 内网机(无网络安装 .NET Core win开发环境

    1.安装 vs2015 update3 2.按顺序安装以下包 DotNetCore.1.0.0-SDK.Preview2-x64.exe aspnetcoremodule_x64_en_rc2_14. ...

  6. 【算法之美】你可能想不到的归并排序的神奇应用 — leetcode 327. Count of Range Sum

    又是一道有意思的题目,Count of Range Sum.(PS:leetcode 我已经做了 190 道,欢迎围观全部题解 https://github.com/hanzichi/leetcode ...

  7. Javascript中判断数组的正确姿势

    在 Javascript 中,如何判断一个变量是否是数组? 最好的方式是用 ES5 提供的 Array.isArray() 方法(毕竟原生的才是最屌的): var a = [0, 1, 2]; con ...

  8. OFFSET IN 使用举例

    本文将结合具体实例阐述OFFSET IN的使用方法.注意:这是我第一次写OFFSET IN约束,本文仅供参考.阅读本文前需要了解时序收敛的基本概念,OFFSET IN和Period的相关知识,可先阅读 ...

  9. 东大OJ-一元三次方程解的个数

    1043: Fixed Point 时间限制: 5 Sec  内存限制: 128 MB 提交: 26  解决: 5 [提交][状态][讨论版] 题目描述 In mathematics, a fixed ...

  10. 由Nullable模式想到的ToString的扩展

    虽然关于null的一切争论永不停息,但根据实际开发经历,很多时候需要判断无聊的null,并且有些的判断是可有可无的,尤其是在表现层. string e = null; if (e != null) { ...