一、springmvc实现文件上传的步骤
1、实现上传单张图片
1、导入pom 坐标
<!--文件上传-->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.3</version>
</dependency>
<!--servlet-api导入高版本的-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
2、编写上传页面
注意:页面上通过 input 来准备 file 组件,该标签必须给定 name 属性值(该 name 不能和实体类的属性名一致),要求 form 表单必须给定一个属性:enctype=“multipart/form-data”,同时请求必须为post:method=“post”
<h2>文件上传</h2>
<form action="up" method="post" enctype="multipart/form-data" >
用户名:<input type="text" name="name" value="jim" /><br/>
头像:<input type="file" name="myfile" /><br/>
<input type="submit" value="上传" />
</form>
3、文件上传配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation=" http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--自动扫描包,让指定包下的注解生效,有IOC容器统一管理-->
<context:component-scan base-package="com.kuang.controller"/>
<!--让springmvc 不处理静态资源-->
<mvc:default-servlet-handler/>
<!--开启注解支持-->
<mvc:annotation-driven>
<!--json乱码问题配置-->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
</bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!--前缀解析器-->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!--后缀解析器-->
<property name="suffix" value=".jsp"></property>
</bean>
<!--文件上传配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 -->
<property name="defaultEncoding" value="utf-8"/>
<!-- 上传文件大小上限,单位为字节(10485760=10M) -->
<property name="maxUploadSize" value="10485760"/>
<property name="maxInMemorySize" value="40960"/>
</bean>
</beans>
4、编写Controller类
@RequestMapping("/up")
public String testUP(@RequestParam CommonsMultipartFile myfile, String name, Model m, HttpSession session) throws Exception{
String realpath = session.getServletContext().getRealPath("\\upload");
System.out.println("上传文件保存地址:"+realpath);
// 获取客户端文件名 hello.jpg 3.jpg
String fname = myfile.getOriginalFilename();
// 以 . 进行分割并截取后面的
String ftype = fname.substring(fname.lastIndexOf("."));
// 生产的不重复的文件名
String filename = UUID.randomUUID().toString();
// 文件名+文件类型
String fullname = realpath+"\\"+filename+ftype;
System.out.println("上传的文件名:"+fname);
// 将上传文件的内容 转成 byte数组
byte[] b = myfile.getBytes();
//将上传的文件输出到磁盘
System.out.println(fullname);
FileOutputStream out = new FileOutputStream(fullname);
out.write(b);
out.flush();
out.close();
m.addAttribute("fname", fname);
return "ok";
}
5、上传成功后跳转的页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%
String fname = (String)request.getAttribute("fname");
%>
<h3>成功上传了一个文件 <%= fname %></h3>
</body>
</html>
效果图:
2、实现上传多张图片
1、编写上传页面
<h2>文件上传多张图片</h2>
<form action="up2" method="post" enctype="multipart/form-data" >
用户名:<input type="text" name="name" value="jim" /><br/>
文件1:<input type="file" name="myfile" /><br/>
文件2:<input type="file" name="myfile" /><br/>
<input type="submit" value="上传" />
</form>
2、编写Controller类
@RequestMapping("/up2")
public String testUP2(@RequestParam CommonsMultipartFile[] myfile, String name, Model m, HttpSession session) throws Exception{
// 用于存放客户端上传的文件名
ArrayList listname =new ArrayList();
// 用于存放服务器端上传的文件名
ArrayList listname2 =new ArrayList();
// File.separator 不同系统的分隔符
String realpath = session.getServletContext().getRealPath(File.separator+"upload");
System.out.println("上传文件保存地址:"+realpath);
for(CommonsMultipartFile cf :myfile){
// 获取客户端文件名 hello.jpg 3.jpg
String fname = cf.getOriginalFilename();
// 以 . 进行分割并截取后面的
String ftype = fname.substring(fname.lastIndexOf("."));
// 生产的不重复的文件名
String filename = UUID.randomUUID().toString();
// 文件名+文件类型
String fullname = realpath+File.separator+filename+ftype;
System.out.println(fname);
//将上传的文件输出到磁盘
System.out.println(fullname);
// 将文件内容输出到指定位置
cf.transferTo(new File(fullname));
listname.add(fname);
listname2.add(filename+ftype);
m.addAttribute("flist", listname);
m.addAttribute("flist2", listname2);
}
return "ok2";
}
3、上传成功后跳转的页面
<%@ page contentType="text/html;charset=UTF-8" import="java.util.*" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
ArrayList flist = (ArrayList)request.getAttribute("flist");
ArrayList flist2 = (ArrayList)request.getAttribute("flist2");
%>
<h3>成功上传了
<%
for(int i = 0 ; i < flist.size() ;i++){
String n = (String)flist.get(i);
%>
<%=n %>,
<%
}
%>文件 </h3>
<hr/>
<%
for(int i = 0 ; i < flist2.size() ;i++){
String name = (String)flist2.get(i);
%>
<img alt="图片加载失败" title="上传的图片" src="<%=request.getContextPath()%>/upload/<%=name%>" />
<%
}
%>
</body>
</html>
二、springmvc实现文件下载的步骤
1、显示所有下载图片
这里我们先显示文件夹中所有的图片,然后在点击单个图片进行下载。
<h2><a href="xzview" >下载页面</a></h2>
2、编写Controller 类
//下载图片前 显示列表
@RequestMapping("/xzview")
public String testXzView(Model m, HttpSession session){
String realpath = session.getServletContext().getRealPath(File.separator+"upload");
File f = new File(realpath);
String[] fs = f.list(); //文件夹中所有的文件名
m.addAttribute("fs", fs);
return "view";
}
//下载图片
@RequestMapping("/xzimgcon")
public void xzimgcon(String fname , HttpServletRequest request, HttpServletResponse response){
response.setContentType("image/jpeg;charset=utf-8");// 服务端以 二进制流的形式 相应客户端
//String spath = request.getSession().getServletContext().getRealPath("img\\");
HttpSession session = request.getSession(); //获取session对象
ServletContext sc = session.getServletContext(); //获取ServletContext对象 Servlet上下文对象
String realpath = sc.getRealPath("upload\\");
//System.out.println(realpath);
//String filename = "1";
response.setHeader("Content-disposition", "attachment;filename=" + fname);
try {
//构建输入流,将磁盘上的文件 读取到程序中
FileInputStream fin = new FileInputStream(realpath + "\\" + fname);
//输出流由response提供,将程序中的字节 输出到 客户端
ServletOutputStream fout = response.getOutputStream();
byte[] b = new byte[fin.available()];
fin.read(b);fout.write(b);fin.close();fout.flush();fout.close();
} catch (Exception e) {
System.out.println("下载文件出现异常");
e.printStackTrace();
}
}
3、实现下载页面
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<h1>下载页面</h1>
<%
String[] fs = (String[])request.getAttribute("fs");
%>
<%
for(int i = 0 ; i < fs.length; i++){
String fname = fs[i];
%>
<img width="100" height="100" src="<%=request.getContextPath()+"/upload/"+fname %>" /><a href="xzimgcon?fname=<%=fname%>">下载</a>
<%
}
%>
</body>
</html>
效果图: