SSM框架-SpringMVC 实例文件上传下载
一、新建一个Web工程,导入相关的包
springmvc的包+commons-fileupload.jar+connom-io.jar+commons-logging,jar+jstl.jar+standard.jar
整个相关的包如下:
整个工程目录如下:
二、配置web.xml和SpringMVC文件
(1)web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!-- SpringMVC的前端控制器 -->
<servlet>
<servlet-name>MyDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 设置自己定义的控制器xml文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Spring MVC配置文件结束 -->
<!-- 拦截设置 -->
<servlet-mapping>
<servlet-name>MyDispatcher</servlet-name>
<!-- 由SpringMVC拦截所有请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!-- SpringMVC的前端控制器 -->
<servlet>
<servlet-name>MyDispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 设置自己定义的控制器xml文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Spring MVC配置文件结束 -->
<!-- 拦截设置 -->
<servlet-mapping>
<servlet-name>MyDispatcher</servlet-name>
<!-- 由SpringMVC拦截所有请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
(2)springMVC-servlet.xml文件
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 把标记了@Controller注解的类转换为bean -->
<context:component-scan base-package="com.mucfc" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>
<!-- 上传文件的设置 ,maxUploadSize=-1,表示无穷大。uploadTempDir为上传的临时目录 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="5400000"
p:uploadTempDir="fileUpload/temp"
/>
</beans>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<!-- 把标记了@Controller注解的类转换为bean -->
<context:component-scan base-package="com.mucfc" />
<!-- 对模型视图名称的解析,即在模型视图名称添加前后缀 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/views/" p:suffix=".jsp"/>
<!-- 上传文件的设置 ,maxUploadSize=-1,表示无穷大。uploadTempDir为上传的临时目录 -->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"
p:defaultEncoding="UTF-8"
p:maxUploadSize="5400000"
p:uploadTempDir="fileUpload/temp"
/>
</beans>
三、单个文件上传
(1)控制器
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/toFile")
public String toFileUpload() {
return "fileUpload";
}
@RequestMapping("/toFile2")
public String toFileUpload2() {
return "fileUpload2";
}
/**
* 方法一上传文件
*/
@RequestMapping("/onefile")
public String oneFileUpload(
@RequestParam("file") CommonsMultipartFile file,
HttpServletRequest request, ModelMap model) {
// 获得原始文件名
String fileName = file.getOriginalFilename();
System.out.println("原始文件名:" + fileName);
// 新文件名
String newFileName = UUID.randomUUID() + fileName;
// 获得项目的路径
ServletContext sc = request.getSession().getServletContext();
// 上传位置
String path = sc.getRealPath("/img") + "/"; // 设定文件保存的目录
File f = new File(path);
if (!f.exists())
f.mkdirs();
if (!file.isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(path + newFileName);
InputStream in = file.getInputStream();
int b = 0;
while ((b = in.read()) != -1) {
fos.write(b);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("上传图片到:" + path + newFileName);
// 保存文件地址,用于JSP页面回显
model.addAttribute("fileUrl", path + newFileName);
return "fileUpload";
}
/**
* 方法二上传文件,一次一张
*/
@RequestMapping("/onefile2")
public String oneFileUpload2(HttpServletRequest request,
HttpServletResponse response) throws Exception {
CommonsMultipartResolver cmr = new CommonsMultipartResolver(
request.getServletContext());
if (cmr.isMultipart(request)) {
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
Iterator<String> files = mRequest.getFileNames();
while (files.hasNext()) {
MultipartFile mFile = mRequest.getFile(files.next());
if (mFile != null) {
String fileName = UUID.randomUUID()
+ mFile.getOriginalFilename();
String path = "d:/upload/" + fileName;
File localFile = new File(path);
mFile.transferTo(localFile);
request.setAttribute("fileUrl", path);
}
}
}
return "fileUpload";
}
}
@Controller
@RequestMapping("/file")
public class FileController {
@RequestMapping("/toFile")
public String toFileUpload() {
return "fileUpload";
}
@RequestMapping("/toFile2")
public String toFileUpload2() {
return "fileUpload2";
}
/**
* 方法一上传文件
*/
@RequestMapping("/onefile")
public String oneFileUpload(
@RequestParam("file") CommonsMultipartFile file,
HttpServletRequest request, ModelMap model) {
// 获得原始文件名
String fileName = file.getOriginalFilename();
System.out.println("原始文件名:" + fileName);
// 新文件名
String newFileName = UUID.randomUUID() + fileName;
// 获得项目的路径
ServletContext sc = request.getSession().getServletContext();
// 上传位置
String path = sc.getRealPath("/img") + "/"; // 设定文件保存的目录
File f = new File(path);
if (!f.exists())
f.mkdirs();
if (!file.isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(path + newFileName);
InputStream in = file.getInputStream();
int b = 0;
while ((b = in.read()) != -1) {
fos.write(b);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("上传图片到:" + path + newFileName);
// 保存文件地址,用于JSP页面回显
model.addAttribute("fileUrl", path + newFileName);
return "fileUpload";
}
/**
* 方法二上传文件,一次一张
*/
@RequestMapping("/onefile2")
public String oneFileUpload2(HttpServletRequest request,
HttpServletResponse response) throws Exception {
CommonsMultipartResolver cmr = new CommonsMultipartResolver(
request.getServletContext());
if (cmr.isMultipart(request)) {
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
Iterator<String> files = mRequest.getFileNames();
while (files.hasNext()) {
MultipartFile mFile = mRequest.getFile(files.next());
if (mFile != null) {
String fileName = UUID.randomUUID()
+ mFile.getOriginalFilename();
String path = "d:/upload/" + fileName;
File localFile = new File(path);
mFile.transferTo(localFile);
request.setAttribute("fileUrl", path);
}
}
}
return "fileUpload";
}
}
(2)JSP,这个页面是用来上传又用来显示上传后的图片的页面fileUpload.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>用户上传图片页面</title>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<form action="file/onefile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<img alt="暂无图片" src="${fileUrl}" />
</center>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>用户上传图片页面</title>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<form action="file/onefile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<img alt="暂无图片" src="${fileUrl}" />
</center>
</body>
</html>
现在运行后来看看效果,输入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile
控制台输出结果,选择图片后
原始文件名:Chrysanthemum.jpg
上传图片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/4eafc28c-4baa-4018-ac06-c4a5aec88d6cChrysanthemum.jpg
图片已被上传,可以在JSP中显示出来
来看看服务器的路径:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img
表明图片已经上传到服务器
方法二:
使用文件流的方式来上传
/**
* 方法二上传文件,一次一张
*/
@RequestMapping("/onefile2")
public String oneFileUpload2(HttpServletRequest request,
HttpServletResponse response) throws Exception {
CommonsMultipartResolver cmr = new CommonsMultipartResolver(
request.getServletContext());
if (cmr.isMultipart(request)) {
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
Iterator<String> files = mRequest.getFileNames();
while (files.hasNext()) {
MultipartFile mFile = mRequest.getFile(files.next());
if (mFile != null) {
String fileName = UUID.randomUUID()
+ mFile.getOriginalFilename();
String path = "d:/upload/" + fileName;
File localFile = new File(path);
mFile.transferTo(localFile);
request.setAttribute("fileUrl", path);
}
}
}
return "fileUpload";
}
/**
* 方法二上传文件,一次一张
*/
@RequestMapping("/onefile2")
public String oneFileUpload2(HttpServletRequest request,
HttpServletResponse response) throws Exception {
CommonsMultipartResolver cmr = new CommonsMultipartResolver(
request.getServletContext());
if (cmr.isMultipart(request)) {
MultipartHttpServletRequest mRequest = (MultipartHttpServletRequest) (request);
Iterator<String> files = mRequest.getFileNames();
while (files.hasNext()) {
MultipartFile mFile = mRequest.getFile(files.next());
if (mFile != null) {
String fileName = UUID.randomUUID()
+ mFile.getOriginalFilename();
String path = "d:/upload/" + fileName;
File localFile = new File(path);
mFile.transferTo(localFile);
request.setAttribute("fileUrl", path);
}
}
}
return "fileUpload";
}
把
<center>
<form action="file/onefile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<img alt="暂无图片" src="${fileUrl}" />
</center>
<center>
<form action="file/onefile"
method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<img alt="暂无图片" src="${fileUrl}" />
</center>
中的
<form action="file/onefile"
<form action="file/onefile"
改成
<form action="file/onefile2"
<form action="file/onefile2"
输入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile
方法二指定上传到了本地E盘的upload文件夹
页面结果
四、多文件上传
(1)控制器
@RequestMapping("/toFile2")
public String toFileUpload2() {
return "fileUpload2";
}
@RequestMapping("/toFile2")
public String toFileUpload2() {
return "fileUpload2";
}
/**
* 一次上传多张图片
*/
@RequestMapping("/threeFile")
public String threeFileUpload(
@RequestParam("file") CommonsMultipartFile files[],
HttpServletRequest request, ModelMap model) {
List<String> list = new ArrayList<String>();
// 获得项目的路径
ServletContext sc = request.getSession().getServletContext();
// 上传位置
String path = sc.getRealPath("/img") + "/"; // 设定文件保存的目录
File f = new File(path);
if (!f.exists())
f.mkdirs();
for (int i = 0; i < files.length; i++) {
// 获得原始文件名
String fileName = files[i].getOriginalFilename();
System.out.println("原始文件名:" + fileName);
// 新文件名
String newFileName = UUID.randomUUID() + fileName;
if (!files[i].isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(path
+ newFileName);
InputStream in = files[i].getInputStream();
int b = 0;
while ((b = in.read()) != -1) {
fos.write(b);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("上传图片到:" + path + newFileName);
list.add(path + newFileName);
}
// 保存文件地址,用于JSP页面回显
model.addAttribute("fileList", list);
return "fileUpload2";
}
/**
* 一次上传多张图片
*/
@RequestMapping("/threeFile")
public String threeFileUpload(
@RequestParam("file") CommonsMultipartFile files[],
HttpServletRequest request, ModelMap model) {
List<String> list = new ArrayList<String>();
// 获得项目的路径
ServletContext sc = request.getSession().getServletContext();
// 上传位置
String path = sc.getRealPath("/img") + "/"; // 设定文件保存的目录
File f = new File(path);
if (!f.exists())
f.mkdirs();
for (int i = 0; i < files.length; i++) {
// 获得原始文件名
String fileName = files[i].getOriginalFilename();
System.out.println("原始文件名:" + fileName);
// 新文件名
String newFileName = UUID.randomUUID() + fileName;
if (!files[i].isEmpty()) {
try {
FileOutputStream fos = new FileOutputStream(path
+ newFileName);
InputStream in = files[i].getInputStream();
int b = 0;
while ((b = in.read()) != -1) {
fos.write(b);
}
fos.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("上传图片到:" + path + newFileName);
list.add(path + newFileName);
}
// 保存文件地址,用于JSP页面回显
model.addAttribute("fileList", list);
return "fileUpload2";
}
其实就是在单文件上传的方法一中来修改的,只不过弄成了个循环
(2)JSP显示页面fileUpload2.jsp
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>用户上传图片页面</title>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<form action="file/threeFile" method="post"
enctype="multipart/form-data">
<input type="file" name="file" /><br /> <input type="file"
name="file" /><br /> <input type="file" name="file" /><br /> <input
type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<c:forEach items="${fileList}" var="imagename">
<img alt="暂无图片" src="${imagename}" /> <br/>
</c:forEach>
</center>
</body>
</html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>用户上传图片页面</title>
<base href="<%=basePath%>">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<center>
<form action="file/threeFile" method="post"
enctype="multipart/form-data">
<input type="file" name="file" /><br /> <input type="file"
name="file" /><br /> <input type="file" name="file" /><br /> <input
type="submit" value="上 传" />
</form>
<h5>上传结果:</h5>
<c:forEach items="${fileList}" var="imagename">
<img alt="暂无图片" src="${imagename}" /> <br/>
</c:forEach>
</center>
</body>
</html>
注意这里用了
</c:forEach>
</c:forEach>
表单,需要jstl.jar+standard.jar
(3)运行后输入:http://localhost:8080/SpringMVCLearningChapter4_1/file/toFile2(注意上面是单文件没有后面的数字2)
选择图片,然后点上传
控制台输出结果:
图片不清看文字 吧:
原始文件名:Desert.jpg
上传图片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/2baccc77-43b6-4908-859d-507e86a04051Desert.jpg
原始文件名:Hydrangeas.jpg
上传图片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/51ad04e0-82aa-4b2c-958d-f00651e9ed6bHydrangeas.jpg
原始文件名:Jellyfish.jpg
上传图片到:E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\SpringMVCLearningChapter4_1\img/dee340d8-9cc0-41ae-9959-f7fa47ff172bJellyfish.jpg
三张图片都可以显示出来了
来看看服务器,这就是刚刚上传的三张
五、上传文件列表显示
(1)控制器
/**
* 列出所有的图片
*/
@RequestMapping("/listFile")
public String listFile(HttpServletRequest request,
HttpServletResponse response) {
// 获取上传文件的目录
ServletContext sc = request.getSession().getServletContext();
// 上传位置
String uploadFilePath = sc.getRealPath("/img") + "/"; // 设定文件保存的目录
// 存储要下载的文件名
Map<String, String> fileNameMap = new HashMap<String, String>();
// 递归遍历filepath目录下的所有文件和目录,将文件的文件名存储到map集合中
listfile(new File(uploadFilePath), fileNameMap);// File既可以代表一个文件也可以代表一个目录
// 将Map集合发送到listfile.jsp页面进行显示
request.setAttribute("fileNameMap", fileNameMap);
return "listFile";
}
/**
* 列出所有的图片
*/
@RequestMapping("/listFile")
public String listFile(HttpServletRequest request,
HttpServletResponse response) {
// 获取上传文件的目录
ServletContext sc = request.getSession().getServletContext();
// 上传位置
String uploadFilePath = sc.getRealPath("/img") + "/"; // 设定文件保存的目录
// 存储要下载的文件名
Map<String, String> fileNameMap = new HashMap<String, String>();
// 递归遍历filepath目录下的所有文件和目录,将文件的文件名存储到map集合中
listfile(new File(uploadFilePath), fileNameMap);// File既可以代表一个文件也可以代表一个目录
// 将Map集合发送到listfile.jsp页面进行显示
request.setAttribute("fileNameMap", fileNameMap);
return "listFile";
}
(2)JSP文件listFile.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<title>下载文件显示页面</title>
</head>
<body>
<!-- 遍历Map集合 -->
<c:forEach var="me" items="${fileNameMap}">
<c:url value="/file/downFile" var="downurl">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
${me.value}<a href="${downurl}">下载</a>
<br/>
</c:forEach>
</body>
</html>
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE HTML>
<html>
<head>
<title>下载文件显示页面</title>
</head>
<body>
<!-- 遍历Map集合 -->
<c:forEach var="me" items="${fileNameMap}">
<c:url value="/file/downFile" var="downurl">
<c:param name="filename" value="${me.key}"></c:param>
</c:url>
${me.value}<a href="${downurl}">下载</a>
<br/>
</c:forEach>
</body>
</html>
(3)运行后输入:http://localhost:8080/SpringMVCLearningChapter4_1/file/listFile
这些为刚刚上传到四张图片。
六、文件下载
(1)控制器
@RequestMapping("/downFile")
public void downFile(HttpServletRequest request,
HttpServletResponse response) {
System.out.println("1");
// 得到要下载的文件名
String fileName = request.getParameter("filename");
System.out.println("2");
try {
fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
System.out.println("3");
// 获取上传文件的目录
ServletContext sc = request.getSession().getServletContext();
System.out.println("4");
// 上传位置
String fileSaveRootPath = sc.getRealPath("/img");
System.out.println(fileSaveRootPath + "\\" + fileName);
// 得到要下载的文件
File file = new File(fileSaveRootPath + "\\" + fileName);
// 如果文件不存在
if (!file.exists()) {
request.setAttribute("message", "您要下载的资源已被删除!!");
System.out.println("您要下载的资源已被删除!!");
return;
}
// 处理文件名
String realname = fileName.substring(fileName.indexOf("_") + 1);
// 设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(realname, "UTF-8"));
// 读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(fileSaveRootPath + "\\" + fileName);
// 创建输出流
OutputStream out = response.getOutputStream();
// 创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
// 循环将输入流中的内容读取到缓冲区当中
while ((len = in.read(buffer)) > 0) {
// 输出缓冲区的内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
// 关闭文件输入流
in.close();
// 关闭输出流
out.close();
} catch (Exception e) {
}
}
@RequestMapping("/downFile")
public void downFile(HttpServletRequest request,
HttpServletResponse response) {
System.out.println("1");
// 得到要下载的文件名
String fileName = request.getParameter("filename");
System.out.println("2");
try {
fileName = new String(fileName.getBytes("iso8859-1"), "UTF-8");
System.out.println("3");
// 获取上传文件的目录
ServletContext sc = request.getSession().getServletContext();
System.out.println("4");
// 上传位置
String fileSaveRootPath = sc.getRealPath("/img");
System.out.println(fileSaveRootPath + "\\" + fileName);
// 得到要下载的文件
File file = new File(fileSaveRootPath + "\\" + fileName);
// 如果文件不存在
if (!file.exists()) {
request.setAttribute("message", "您要下载的资源已被删除!!");
System.out.println("您要下载的资源已被删除!!");
return;
}
// 处理文件名
String realname = fileName.substring(fileName.indexOf("_") + 1);
// 设置响应头,控制浏览器下载该文件
response.setHeader("content-disposition", "attachment;filename="
+ URLEncoder.encode(realname, "UTF-8"));
// 读取要下载的文件,保存到文件输入流
FileInputStream in = new FileInputStream(fileSaveRootPath + "\\" + fileName);
// 创建输出流
OutputStream out = response.getOutputStream();
// 创建缓冲区
byte buffer[] = new byte[1024];
int len = 0;
// 循环将输入流中的内容读取到缓冲区当中
while ((len = in.read(buffer)) > 0) {
// 输出缓冲区的内容到浏览器,实现文件下载
out.write(buffer, 0, len);
}
// 关闭文件输入流
in.close();
// 关闭输出流
out.close();
} catch (Exception e) {
}
}
这里就是通过文件流的方式来下载图片的。
然后就可以自己选择下载的地方了。
终于讲完了,花了大半天啊!
SSM框架-SpringMVC 实例文件上传下载的更多相关文章
- Selenium2学习-039-WebUI自动化实战实例-文件上传下载
通常在 WebUI 自动化测试过程中必然会涉及到文件上传的自动化测试需求,而开发在进行相应的技术实现是不同的,粗略可划分为两类:input标签类(类型为file)和非input标签类(例如:div.a ...
- ssm框架下实现文件上传
1.由于ssm框架是使用Maven进行管理的,文件上传所需要的jar包利用pom.xml进行添加,如下所示: <properties> <commons-fileupload.v ...
- springMVC实现文件上传下载
上传文件和下载文件是个常用的技能,在哪里开发几乎都能遇见,而所有的上传控件各不相同,插件很多,后台也有很多,这里我只尝试过这个方法觉的还够简洁.具体如下实现: 1.spring-mvc.xml配置 ...
- ssm框架下的文件上传和文件下载
最近在做一个ssm的项目,遇到了添加附件和下载的功能,在网上查了很多资料,发现很多都不好用,经过摸索,发现了一套简便的方法,和大家分享一下. 1.在自己已经构建好的maven web项目中 pom. ...
- 14.SpringMVC之文件上传下载
SpringMVC通过MultipartResolver(多部件解析器)对象实现对文件上传的支持. MultipartResolver是一个接口对象,需要通过它的实现类CommonsMultipart ...
- SpringMVC的文件上传下载,异常处理,拦截器的小总结
文件的上传和下载 我们通常在访问网页时会使用到文件的上传与下载的功能,那么他是如何实现的呢? 1 下载: ResponseEntity :用于控制器方法的返回值类型,该控制器方法的返回值就是响应到浏览 ...
- SpringMVC异步文件上传下载
首先了解一下File的构造方法: File(String pathname):根据一个路径得到File对象 File(String parent,String child):根据一个目录和一个子文件/ ...
- SpringMVC文件上传下载(单文件、多文件)
前言 大家好,我是bigsai,今天我们学习Springmvc的文件上传下载. 文件上传和下载是互联网web应用非常重要的组成部分,它是信息交互传输的重要渠道之一.你可能经常在网页上传下载文件,你可能 ...
- springmvc文件上传下载简单实现案例(ssm框架使用)
springmvc文件上传下载实现起来非常简单,此springmvc上传下载案例适合已经搭建好的ssm框架(spring+springmvc+mybatis)使用,ssm框架项目的搭建我相信你们已经搭 ...
随机推荐
- [No0000137]字符编码详解
摘要 本文主要介绍了字符编码的基础知识,以及常见的字符编码类型,比如ASCII,Unicode,UTF-8,ISO 8859等,以及各种编码之间的关系,同时专门解释了中文字符相关的编码标准,包括GB2 ...
- Js高设笔记 & 声明变量与初始化变量
第三章 数据类型 P25 1, var message; //age变量尚未声明 alert(message); //"undefined" alert(age); ...
- vue中导入外面文件(css,js)方式
有时我们需要导入外面的css文件(例如reset.css文件,bootstrap.css,jQuery.js文件),通常可通过import "name.css"的形式 对于rese ...
- cocoapods 无法 升级 repo 无法执行pod install命令
首先MAC自带了ruby,他是用rvm 管理的, 如果你用homebrew又安装了一个新版,很可能在升级cocoapods时遇到问题,明明自己用homebrew升级到最新版本了,页配置环境变量了,为什 ...
- VS2015工具箱不出现ArcGIS Windows Forms怎么办?
原文: https://blog.csdn.net/pangpi814961437/article/details/7954033
- C# Winform同一子窗体只允许打开一次
在winform中一个窗口可以一直打开,是不合理的,解决方法: http://blog.csdn.net/kangkang621/article/details/49664295
- User-Defined Variables
mysql> SET @w := SELECT COUNT(*) FROM course WHERE cteacher='程军'; ERROR (): You have an error in ...
- Laravel 5.2 INSTALL- node's npm and ruby's bundler.
https://getcomposer.org/doc/00-intro.md Introduction# Composer is a tool for dependency management i ...
- [skill][funny] 一个很厉害的for循环
int DSSL_MoveServerToMissingKeyList( DSSL_Env* env, DSSL_ServerInfo* si ) { DSSL_ServerInfo** new_se ...
- 【Linux】Linux 常用命令汇总
查看软件xxx安装内容:dpkg -L xxx 查找软件库中的软件:apt-cache search 正则表达式 查找软件库中的软件:aptitude search 软件包 查找文件属于哪个包:dpk ...