前言

文件上传是项目开发中最常见的功能。为了能上传文件,必须将表单的method设置为POST,并将enctype设置为multipart/form-data。只有在这样的情况下,浏览器才会把用户选择的文件以二进制数据发送给服务器。 设置了enctype为multipart/form-data,浏览器才会采用二进制流的方式来处理表单数据,而对于文件上传的处理则涉及在服务器端解析原始的HTTP响应。下面我们来学习使用SpringMVC框架完成文件的上传以及下载。

单文件上传

Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。Spring MVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。因此,SpringMVC的文件上传还需要依赖 Apache Commons FileUpload 的组件。

1、引入Apache Commons FileUpload组件的依赖

  <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>1.3.2</version>
    </dependency>

    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.1</version>
    </dependency>

2、springmvc.xml配置CommonsMultipartResolver

    <!-- 配置CommonsMultipartResolver bean,id必须是multipartResolver -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 处理文件名中文乱码 -->
        <property name="defaultEncoding" value="utf-8"/>
        <!-- 设置多文件上传,总大小上限,不设置默认没有限制,单位为字节,1M=1*1024*1024 -->
        <property name="maxUploadSize" value="41943040"/>
        <!-- 设置每个上传文件的大小上限 -->
        <property name="maxUploadSizePerFile" value="1048576"/>
    </bean>

    <!-- 设置异常解析器 -->
    <bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
        <property name="defaultErrorView" value="error"/>
    </bean>

3、编写业务方法

将MultipartFile对象作为参数,接收前端发送过来的文件,并编写上传逻辑

	@RequestMapping(value="/upload", method = RequestMethod.POST)
	public String upload(@RequestParam(value="image")MultipartFile image, HttpServletRequest request)
			throws Exception {
		//获取保存上传文件的upload文件夹绝对路径
		String path = request.getSession().getServletContext().getRealPath("upload");
		//判断upload文件夹是否存在,不存在新建文件夹
		File directory = new File(path);
		if (!directory.exists()){
			directory.mkdir();
		}
		//getSize()方法获取文件的大小来判断是否有上传文件
		if (image.getSize() > 0) {
			//获取上传文件名
			String fileName = image.getOriginalFilename();
			File file = new File(path, fileName);
			image.transferTo(file);
			//保存上传之后的文件路径
			request.setAttribute("filePath", "upload/"+fileName);
			return "upload";
		}
		return "error";
	}

4、创建upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试单文件上传</title>
</head>
<body>
	<form action="upload" method="post" enctype="multipart/form-data">
	    <input type="file" name="image">
	    <input type="submit" name="提交">
	</form><br /> 
	<c:if test="${filePath!=null }">
		<h1>上传的图片</h1><br /> 
		<img width="300px" src="<%=basePath %>${filePath}"/>
	</c:if>
</body>
</html>

注意: 必须将表单的method设置为POST(GET请求只会将文件名传给后台),input的type设置为file,并将enctype设置为multipart/form-data。

如果上传成功,返回当前页面,展示上传成功的图片,这里需要使用JSTL标签进行判断。JSP标准标签库(JSTL)是一个JSP标签集合,它封装了JSP应用的通用核心功能。

在pom文件中引入JSTL依赖。

    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>
  </dependencies>

5、运行
SpringMVC学习(6):文件上传与下载
SpringMVC学习(6):文件上传与下载

多文件上传

1、编写业务方法

	@RequestMapping(value="/uploads", method = RequestMethod.POST)
	public String uploads(@RequestParam(value="images") MultipartFile[] images, HttpServletRequest request)
			throws Exception {
		String path = request.getSession().getServletContext().getRealPath("upload");
		File directory = new File(path);
		if (!directory.exists()){
			directory.mkdir();
		}
		//创建集合,保存上传后的文件路径
		List<String> filePaths = new ArrayList<String>();
		System.out.println(images);
		for (MultipartFile image : images) {
			if (image.getSize() > 0) {
				String fileName = image.getOriginalFilename();
				File file = new File(path, fileName);
				filePaths.add("upload/"+fileName);
				image.transferTo(file);
			}
		}
		request.setAttribute("filePaths", filePaths);
		return "uploads";
	}

2、创建uploads.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%
	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>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>测试多文件上传</title>
</head>
<body>
	<form action="uploads" method="post" enctype="multipart/form-data">
	    文件1:&nbsp&nbsp<input type="file" name="images"><br/>
		文件2:&nbsp&nbsp<input type="file" name="images"><br/>
		文件3:&nbsp&nbsp<input type="file" name="images"><br/>
	    <input type="submit" name="提交">
	</form>
	<c:if test="${filePaths!=null }">
		<h1>上传的图片</h1><br /> 
		<c:forEach items="${filePaths }" var="filePaths">
			<img width="300px" src="<%=basePath %>${filePaths}"/>
		</c:forEach>
	</c:if>
</body>
</html>

3、运行
SpringMVC学习(6):文件上传与下载
SpringMVC学习(6):文件上传与下载

文件下载

1、编写业务方法

	@RequestMapping("/download")
	public void downloadFile(String fileName,HttpServletRequest request, HttpServletResponse response){
		if(fileName!=null){
			//获取file绝对路径
			String realPath = request.getServletContext().getRealPath("upload/");
			File file = new File(realPath,fileName);
			OutputStream out = null;
			if(file.exists()){
				//设置下载完毕不打开文件
				response.setContentType("application/force-download");
				//设置文件名
				response.setHeader("Content-Disposition", "attachment;filename="+fileName);
				try {
					out = response.getOutputStream();
					out.write(FileUtils.readFileToByteArray(file));
					out.flush();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}finally{
					if(out != null){
						try {
							out.close();
						} catch (IOException e) {
							// TODO Auto-generated catch block
							e.printStackTrace();
						}
					}
				}
			}
		}
	}

2、创建download.jsp

<%@ 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>测试文件下载</title>
</head>
<body>
	<a href="download?fileName=logo.jpg">下载图片</a>
</body>
</html>

3、运行
SpringMVC学习(6):文件上传与下载
SpringMVC学习(6):文件上传与下载

源码

链接:
https://pan.baidu.com/s/1ODnsGs4mBUFaUxgYEwCLqg
提取码:6rjh


相关文章: