开始需要在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>密&nbsp;码:</label><input type="password" name="password"/><br/>
<label>头&nbsp;像</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>密&nbsp;码:</label><input type="password" name="password"/><br/>
<label>头&nbsp;像1</label><input type="file" name="file"/><br/>
<label>头&nbsp;像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";
}
}

最新文章

  1. Structure Of Management Information - SNMP Tutorial
  2. git http\https\git免密设置记住用户名和密码的方法
  3. AX2012 R3 Data upgrade checklist sync database step, failed to create a session;
  4. MySQL主备库切换(MHA)演练与总结
  5. 关于Linux下C编译错误(警告)cast from &#39;void*&#39; to &#39;int&#39; loses precision
  6. Oracle 显示时间问题
  7. Oracle学习笔记4 使用Navicat for Oracle 连接Oracle时出现错误:ORA-28547: connection to server failed, probable Oracle Net admin error
  8. C#引用传递
  9. 解密-神秘的 RunLoop
  10. awk 的逻辑运算字符
  11. CLR类型设计之类型之常量和字段
  12. 0. Java虚拟机系列备忘预览图
  13. Makefile ------ .PHONY的作用
  14. [原创]Eclipse Memory Analyzer tool(MAT)工个使用介绍
  15. C#程序分析
  16. 微信小程序,创业新选择
  17. [翻译] NSDate-TimeAgo
  18. bootstrap模板
  19. vue slot slot-scope
  20. swift基础-2

热门文章

  1. 解决打包时IsCmdBld.exe出错的问题
  2. Union - Find 、 Adjacency list 、 Topological sorting Template
  3. Windows8下通过IPv4地址访问Tomcat
  4. Navicat连接oracle,出现Only compatible with oci version 8.1 and&amp;amp;nb
  5. codeforces #267 C George and Job(DP)
  6. js轮盘抽奖
  7. Swift - 设置应用程序图标的提醒个数(右上角小红圈)
  8. 动手学Javascript(1)——PopStar
  9. os内存使用管理之unix-AIX篇
  10. 实战ajax