springmvc上传图片并显示图片--支持多图片上传
实现上传图片功能在Springmvc中很好实现。现在我将会展现完整例子。
开始需要在pom.xml加入几个jar,分别是:
- <dependency>
- <groupId>commons-fileupload</groupId>
- <artifactId>commons-fileupload</artifactId>
- <version>1.3.1</version>
- </dependency>
- <dependency>
- <groupId>commons-io</groupId>
- <artifactId>commons-io</artifactId>
- <version>2.4</version>
- </dependency>
接下来,在Springmvc的配置加入上传文件的配置(PS:我把springmvc的完整配置都展现出来):
- <!--默认的mvc注解映射的支持 -->
- <mvc:annotation-driven/>
- <!-- 处理对静态资源的请求 -->
- <mvc:resources location="/static/" mapping="/static/**" />
- <!-- 扫描注解 -->
- <context:component-scan base-package="com.ztz.springmvc.controller"/>
- <!-- 视图解析器 -->
- <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
- <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
- <!-- 前缀 -->
- <property name="prefix" value="/WEB-INF/jsp/"/>
- <!-- 后缀 -->
- <property name="suffix" value=".jsp"/>
- </bean>
- <!-- 上传文件 -->
- <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
- <property name="defaultEncoding" value="utf-8"/>
- <!-- 最大内存大小 -->
- <property name="maxInMemorySize" value="10240"/>
- <!-- 最大文件大小,-1为不限制大小 -->
- <property name="maxUploadSize" value="-1"/>
- </bean>
一、 单文件上传
当然在一个表单中,需要添加enctype="multipart/form-data",一个表单有文件域,肯定也有基本的文本框,可以一次性提交,springmvc能给我们区别出来,来做不同的处理。首先看下普通的model
- package com.ztz.springmvc.model;
- public class Users {
- private String name;
- private String password;
- //省略get set方法
- //重写toString()方便测试
- @Override
- public String toString() {
- return "Users [name=" + name + ", password=" + password + "]";
- }
- }
这个是表单的JSP页面:
- <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- request.setAttribute("basePath", basePath);
- %>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>FileUpload</title>
- </head>
- <body>
- <form action="${basePath}file/upload" method="post" enctype="multipart/form-data">
- <label>用户名:</label><input type="text" name="name"/><br/>
- <label>密 码:</label><input type="password" name="password"/><br/>
- <label>头 像</label><input type="file" name="file"/><br/>
- <input type="submit" value="提 交"/>
- </form>
- </body>
- </html>
上传成功跳转的JSP页面,并且显示出上传图片:
- <%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%>
- <%@taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
- <%
- String path = request.getContextPath();
- String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
- request.setAttribute("basePath", basePath);
- %>
- <!DOCTYPE html>
- <html>
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
- <title>头像</title>
- </head>
- <body>
- <img src="${basePath}${imagesPath}">
- </body>
- </html>
最后是Controller:
- package com.ztz.springmvc.controller;
- import java.io.File;
- import java.util.UUID;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- import com.ztz.springmvc.model.Users;
- @Controller
- @RequestMapping("/file")
- public class FileUploadController {
- @RequestMapping(value="/upload",method=RequestMethod.POST)
- private String fildUpload(Users users ,@RequestParam(value="file",required=false) MultipartFile file,
- HttpServletRequest request)throws Exception{
- //基本表单
- System.out.println(users.toString());
- //获得物理路径webapp所在路径
- String pathRoot = request.getSession().getServletContext().getRealPath("");
- String path="";
- if(!file.isEmpty()){
- //生成uuid作为文件名称
- String uuid = UUID.randomUUID().toString().replaceAll("-","");
- //获得文件类型(可以判断如果不是图片,禁止上传)
- String contentType=file.getContentType();
- //获得文件后缀名称
- String imageName=contentType.substring(contentType.indexOf("/")+1);
- path="/static/images/"+uuid+"."+imageName;
- file.transferTo(new File(pathRoot+path));
- }
- System.out.println(path);
- request.setAttribute("imagesPath", path);
- return "success";
- }
- //因为我的JSP在WEB-INF目录下面,浏览器无法直接访问
- @RequestMapping(value="/forward")
- private String forward(){
- return "index";
- }
- }
点击提交控制台输出:
Users [name=fileupload, password=test]
浏览器显示结果:
二、 多图片上传
springmvc实现多图片上传也很简单,我们把刚才的例子修改下,在加一个文件域,name的值还是相同
- <body>
- <form action="${basePath}file/upload" method="post" enctype="multipart/form-data">
- <label>用户名:</label><input type="text" name="name"/><br/>
- <label>密 码:</label><input type="password" name="password"/><br/>
- <label>头 像1</label><input type="file" name="file"/><br/>
- <label>头 像2</label><input type="file" name="file"/><br/>
- <input type="submit" value="提 交"/>
- </form>
- </body>
展示图片来个循环,以便显示多张图片
- <body>
- <c:forEach items="${imagesPathList}" var="image">
- <img src="${basePath}${image}"><br/>
- </c:forEach>
- </body>
控制层代码如下:
- package com.ztz.springmvc.controller;
- import java.io.File;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.UUID;
- import javax.servlet.http.HttpServletRequest;
- import org.springframework.stereotype.Controller;
- import org.springframework.web.bind.annotation.RequestMapping;
- import org.springframework.web.bind.annotation.RequestMethod;
- import org.springframework.web.bind.annotation.RequestParam;
- import org.springframework.web.multipart.MultipartFile;
- import com.ztz.springmvc.model.Users;
- @Controller
- @RequestMapping("/file")
- public class FileUploadController {
- @RequestMapping(value="/upload",method=RequestMethod.POST)
- private String fildUpload(Users users ,@RequestParam(value="file",required=false) MultipartFile[] file,
- HttpServletRequest request)throws Exception{
- //基本表单
- System.out.println(users.toString());
- //获得物理路径webapp所在路径
- String pathRoot = request.getSession().getServletContext().getRealPath("");
- String path="";
- List<String> listImagePath=new ArrayList<String>();
- for (MultipartFile mf : file) {
- if(!mf.isEmpty()){
- //生成uuid作为文件名称
- String uuid = UUID.randomUUID().toString().replaceAll("-","");
- //获得文件类型(可以判断如果不是图片,禁止上传)
- String contentType=mf.getContentType();
- //获得文件后缀名称
- String imageName=contentType.substring(contentType.indexOf("/")+1);
- path="/static/images/"+uuid+"."+imageName;
- mf.transferTo(new File(pathRoot+path));
- listImagePath.add(path);
- }
- }
- System.out.println(path);
- request.setAttribute("imagesPathList", listImagePath);
- return "success";
- }
- //因为我的JSP在WEB-INF目录下面,浏览器无法直接访问
- @RequestMapping(value="/forward")
- private String forward(){
- return "index";
- }
- }
PS:本demo地址:http://download.csdn.net/detail/zwz568017880/9043089
springmvc上传图片并显示图片--支持多图片上传的更多相关文章
- Jquery图片上传组件,支持多文件上传
Jquery图片上传组件,支持多文件上传http://www.jq22.com/jquery-info230jQuery File Upload 是一个Jquery图片上传组件,支持多文件上传.取消. ...
- ajax 提交所有表单内容及上传图片(文件),以及单独上传某个图片(文件)
我以演示上传图片为例子: java代码如下(前端童鞋可以直接跳过看下面的html及js): package com.vatuu.web.action; import java.io.File; imp ...
- PHP 图片上传工具类(支持多文件上传)
====================ImageUploadTool======================== <?php class ImageUploadTool { private ...
- php 图片上传 并返回上传文件位置 支持多文件上传
<?php /** * Created by PhpStorm. * User: DY040 * Date: 2018/4/26 * Time: 13:23 */ echo '<pre&g ...
- 适应各浏览器图片裁剪无刷新上传jQuery插件(转)
看到一篇兼容性很强的图片无刷新裁剪上传的帖子,感觉很棒.分享下!~ 废话不多说,上效果图. 一.首先建立如下的一个page <!DOCTYPE html> <html xmlns=& ...
- puzz: 图片和表单上传的不一致问题
1. 方向1 用户提交表单, 图片和表单同步上传.(由同一服务器处理, 服务器压力大. 没有分离) 2. 方向2 图片和表单分开上传. 如图片访问ftp,表单提交后台(图片和后台分离) 2 ...
- 移动前端—H5实现图片先压缩再上传
在做移动端图片上传的时候,用户传的都是手机本地图片,而本地图片一般都相对比较大,拿iphone6来说,平时拍很多图片都是一两M的,如果直接这样上传,那图片就太大了,如果用户用的是移动流量,完全把图片上 ...
- 使用html5 FileReader获取图片,并异步上传到服务器(不使用iframe)
使用html5 FileReader获取图片,并异步上传到服务器(不使用iframe) 原理: 1.使用FileReader 读取图片的base64编码 2.使用ajax,把图片的base64编码 ...
- #添加图片,最多只能上传9张.md
#添加图片,最多只能上传9张.md 前端页面: ```javascript <form id="imgForm" enctype="multipart/form-d ...
- 使用html5 FileReader获取图片,并异步上传到server(不使用iframe)
使用html5 FileReader获取图片,并异步上传到server(不使用iframe) 原理: 1.使用FileReader 读取图片的base64编码 2.使用ajax.把图片的base64编 ...
随机推荐
- window对象的inner/outer/page/screen详解
innerHeight : 返回窗口的文档显示区的高度,包含工具条与滚动条.说明:ie8以下不支持 outerHeight : 返回窗口的外部高度,包含工具条与滚动条.说明:ie8以下不支持 page ...
- php配置rewrite模块
转 (1) 启用rewrite模块,在默认情况下,没有启用 修改httpd.conf文件 #启动rewrite模块 LoadModule rewrite_module modules/mod_r ...
- php正则表达式治疗结巴
用正则表达式去解决结巴这个问题可以通过下面进行解决: 解决思路是: 先找到重复的不部分 用str_replace($source,$replace,$str);来进行代理 下面分两种情况,最后将这两种 ...
- workqueue机制分析之process_one_work分析
工作者线程不断执行,从work_poll结构中卸下一个work, 然后进入函数process_one_work 来执行这个work. process_one_work(struct worker *w ...
- 内网机(无网络安装 .NET Core win开发环境
1.安装 vs2015 update3 2.按顺序安装以下包 DotNetCore.1.0.0-SDK.Preview2-x64.exe aspnetcoremodule_x64_en_rc2_14. ...
- 【算法之美】你可能想不到的归并排序的神奇应用 — leetcode 327. Count of Range Sum
又是一道有意思的题目,Count of Range Sum.(PS:leetcode 我已经做了 190 道,欢迎围观全部题解 https://github.com/hanzichi/leetcode ...
- Javascript中判断数组的正确姿势
在 Javascript 中,如何判断一个变量是否是数组? 最好的方式是用 ES5 提供的 Array.isArray() 方法(毕竟原生的才是最屌的): var a = [0, 1, 2]; con ...
- OFFSET IN 使用举例
本文将结合具体实例阐述OFFSET IN的使用方法.注意:这是我第一次写OFFSET IN约束,本文仅供参考.阅读本文前需要了解时序收敛的基本概念,OFFSET IN和Period的相关知识,可先阅读 ...
- 东大OJ-一元三次方程解的个数
1043: Fixed Point 时间限制: 5 Sec 内存限制: 128 MB 提交: 26 解决: 5 [提交][状态][讨论版] 题目描述 In mathematics, a fixed ...
- 由Nullable模式想到的ToString的扩展
虽然关于null的一切争论永不停息,但根据实际开发经历,很多时候需要判断无聊的null,并且有些的判断是可有可无的,尤其是在表现层. string e = null; if (e != null) { ...