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";
}
}
二、 多图片上传
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";
}
}
springmvc上传图片并显示--支持多图片上传的更多相关文章
- springmvc上传图片并显示图片--支持多图片上传
实现上传图片功能在Springmvc中很好实现.现在我将会展现完整例子. 开始需要在pom.xml加入几个jar,分别是: <dependency> <groupId>comm ...
- springMVC框架下——通用接口之图片上传接口
我所想要的图片上传接口是指服务器端在完成图片上传后,返回一个可访问的图片地址. spring mvc框架下图片上传非常简单,如下 @RequestMapping(value="/upload ...
- Ionic3学习笔记(十二)拍照上传图片以及从相册选择图片上传
本文为原创文章,转载请标明出处 目录 安装插件 导入 app.module.ts 创建 provider 更多 效果图 1. 安装插件 终端运行: ionic cordova plugin add c ...
- Ueditor1.4.3.3+springMvc+maven 实现图片上传
前记:由于项目中需要有一个新增数据并且要能支持表格图片上传的功能.使用了ueditor控件.为实现这个功能,从一开始什么都看不懂,到一直连着弄了5天,总算是有了眉目.在此记录一下以便能帮到可以和我一样 ...
- ASP.Net MVC3 图片上传详解(form.js,bootstrap)
图片上传的插件很多,但很多时候还是不能切合我们的需求,我这里给大家分享个我用一个form,file实现上传四张图片的小demo.完全是用jquery前后交互,没有用插件. 最终效果图如下: 玩过花田人 ...
- asp.net多图片上传实现程序代码
下面是一个完整的asp.net同时支持多图片上传一个实现,有需要的朋友可参考一下,本文章限制同时可上传8张图片,当然大可自己可修改更多或更少. 前台代码如下: 复制代码代码如下: <% @ Pa ...
- [上传下载] C# ImageUpload图片上传类教程与源码下载 (转载)
点击下载 ImageUpload.zip 功能如下图片1.设置属性后上传图片,用法如下 /// <summary> /// 图片上传类 /// </summary> //--- ...
- thinkphp微信开发之jssdk图片上传并下载到本地服务器
public function test2(){ $Weixin = new \Weixin\Controller\BaseController(); $this->assign('signPa ...
- [csdn markdown]使用摘记一源代码高亮及图片上传和链接
本文主要内容是体验csdn markdown的代码块高亮显示和图片链接及上传. 图片上传 上边这是标题行,只需要使用一个#就可以表示,几个表示是几级标题 图片上传 本地图片上传控件 本地图片上传方式 ...
随机推荐
- Sleep 和 Wait 关于锁释放的区别
sleep和wait的区别是一个老生常谈的问题.Sleep 是 Thread类的方法, wait是Object类的方法.但是关键的区别是对锁的操作问题. 当我们调用sleep的时候,线程进入休眠,但是 ...
- LoadRunner性能测试之常见函数及参数的说明和作用
- 01、Scala介绍与安装
01.Scala介绍与安装 1.1 Scala介绍 Scala是对java语言脚本化,特点是就是使不具备脚本化的java语言能够采用脚本化方式来使用,使其具有脚本语言简单.所见即所得的特点,并且编程效 ...
- Java中的字符集
Java中的字符集 1.字符集概述 字符集是各国家文字与字符编码对照表.字符可以看成是计算机中展示的图案效果,每个字符集都对每一种图案进行编码,有着一对一的对应关系.因此进行字符输出时,都需要指定使用 ...
- 02、体验Spark shell下RDD编程
02.体验Spark shell下RDD编程 1.Spark RDD介绍 RDD是Resilient Distributed Dataset,中文翻译是弹性分布式数据集.该类是Spark是核心类成员之 ...
- 笨办法学Python(二十五)
习题 25: 更多更多的练习 我们将做一些关于函数和变量的练习,以确认你真正掌握了这些知识.这节练习对你来说可以说是一本道:写程序,逐行研究,弄懂它. 不过这节练习还是有些不同,你不需要运行它,取而代 ...
- 创建React工程:React工程模板
这是本人初学React做的学习笔记;讲的不是很深,只算是简单的进行介绍. 这是一个小系列.都是在同一个模板中搭建的,但是代码是不能正常执行的. >>index.js <!DOCTYP ...
- 2019.03.13 ZJOI2019模拟赛 解题报告
得分: \(55+12+10=77\)(\(T1\)误认为有可二分性,\(T2\)不小心把\(n\)开了\(char\),\(T3\)直接\(puts("0")\)水\(10\)分 ...
- IIS/IIS Express中遇到的证书问题
上面这幅图大家应该不陌生(觉得陌生的话就不用看下面的内容了,呵呵),再放上中英两段关键字: 根据验证过程,远程证书无效. The remote certificate is invalid accor ...
- cudaMalloc和cudaMallocPitch
原文链接 偶有兴趣测试了一下题目中提到的这两个函数,为了满足对齐访问数据,咱们平时可能会用到cudamallocPitch,以为它会带来更高的效率.呵呵,这里给出一段测试程序,大家可以在自己的机器上跑 ...