Spring4 MVC 多文件上传(图片并展示)
开始需要在pom.xml加入几个jar,分别是
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.</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=""/>
<!-- 最大文件大小,-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("/")+);
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("/")+);
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";
}
}
Spring4 MVC 多文件上传(图片并展示)的更多相关文章
- MVC图片上传、浏览、删除 ASP.NET MVC之文件上传【一】(八) ASP.NET MVC 图片上传到服务器
MVC图片上传.浏览.删除 1.存储配置信息 在web.config中,添加配置信息节点 <appSettings> <add key="UploadPath" ...
- MVC之文件上传1
MVC之文件上传 前言 这一节我们来讲讲在MVC中如何进行文件的上传,我们逐步深入,一起来看看. Upload File(一) 我们在默认创建的项目中的Home控制器下添加如下: public Act ...
- Spring MVC的文件上传和下载
简介: Spring MVC为文件上传提供了直接的支持,这种支持使用即插即用的MultipartResolver实现的.Spring MVC 使用Apache Commons FileUpload技术 ...
- 0062 Spring MVC的文件上传与下载--MultipartFile--ResponseEntity
文件上传功能在网页中见的太多了,比如上传照片作为头像.上传Excel文档导入数据等 先写个上传文件的html <!DOCTYPE html> <html> <head&g ...
- Spring MVC实现文件上传
基础准备: Spring MVC为文件上传提供了直接支持,这种支持来自于MultipartResolver.Spring使用Jakarta Commons FileUpload技术实现了一个Multi ...
- Asp.net mvc 大文件上传 断点续传
Asp.net mvc 大文件上传 断点续传 进度条 概述 项目中需要一个上传200M-500M的文件大小的功能,需要断点续传.上传性能稳定.突破asp.net上传限制.一开始看到51CTO上的这 ...
- Spring MVC的文件上传
1.文件上传 文件上传是项目开发中常用的功能.为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data.只有在这种情况下,浏览器才会把用户 ...
- 整合MVC实现文件上传
1.整合MVC实现文件上传整合MVC实现文件上传在实际的开发中在实现文件上传的同时肯定还有其他信息需要保存到数据库,文件上传完毕之后需要将提交的基本信息插入数据库,那么我们来实现这个操作.整个MVC实 ...
- 【Spring学习笔记-MVC-13】Spring MVC之文件上传
作者:ssslinppp 1. 摘要 Spring MVC为文件上传提供了最直接的支持,这种支持是通过即插即用的MultipartResolve实现的.Spring使用Jakarta Co ...
随机推荐
- Android:Notification的生成与取消
MainActivity.java: package com.example.notificationdemo; import android.app.Activity; import android ...
- nginx 解决400 bad request 的方法
nginx的400错误比较难查找原因,因为此错误并不是每次都会出现的,另外,出现错误的时候,通常在浏览器和日志里看不到任何有关提示. 经长时间观察和大量试验查明,此乃request header过大所 ...
- Homebrew 1.0.0 发布,MacOS 上的包管理器
神器,没有它不知道怎么用macos https://www.oschina.net/news/77367/homebrew-1-0-0
- Android GsonUtils工具类
有那么一个开源jar包,叫gson 可以很方便的将java中的对象和字符串相互转化,数据传输和处理的时候,用到的可能性很大 https://github.com/google/gson http:// ...
- python进阶十_正則表達式(一)
近期状态一直不太好,至于原因,怎么说呢,不好说,总之就是纠结中覆盖着纠结,心思全然不在点上,希望能够借助Python的学习以及博客的撰写来调整回来,有的时候回头想一想,假设真的是我自己的问题呢,曾经我 ...
- HDU1058 Humble Numbers 【数论】
Humble Numbers Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others) T ...
- Oracle数据库索引使用及索引失效总结
容易引起oracle索引失效的原因很多: 1.在索引列上使用函数.如SUBSTR,DECODE,INSTR等,对索引列进行运算.需要建立函数索引就可以解决了. 2.新建的表还没来得及生成统计信息,分析 ...
- EasyUI - ValidateBox 验证组件
基本效果: 效果: Html代码: <input id="email" /> JS代码: 默认的有四种验证方式: email:验证邮箱 url:验证url length ...
- 一些实用的mysql语句(不断积累更新)
1.数据表里仅仅有生日字段,想计算出其年龄的mysql语句: SELECT *,DATE_FORMAT(FROM_DAYS(TO_DAYS(NOW( ))-TO_DAYS(生日字段)),'%Y')+0 ...
- Unity3D NGUI,uGUI总结
跪求官方UI系统(2014年11月底已出,用原生的比用NGUI放心) uGUI注意点 1.要防止多个canvas叠加点击穿透,canvas里面的graphics raycaster调整到恰当选项 2. ...