文件上传与下载
文件上传
在 SpringMVC 中提供了用于处理文件上传的组件 CommonsMultipartResolver(多部件解析器)。可以通过该组件很方便的实现文件上传。该组件的运行需要依赖于 Apache 的 commons-fileupload 与 commons-io 包。
搭建环境
- 添加 springmvc 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 配置注解扫描-->
<context:component-scan base-package="com.lanh.web.controller"/>
<!--配置注解驱动-->
<mvc:annotation-driven/>
<!--配置视图解析器-->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewR esolver">
<property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/>
</bean>
<!--配置多部件解析器-->
<!--多部件解析器的 id 必须为 multipartResolver-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipart Resolver">
<!-- 设置上传文件总容量。单位字节 10M = 10*1024*1024-->
<property name="maxUploadSize" value="10485760"/>
<!--设置文件名的编码方式-->
<property name="defaultEncoding" value="utf-8"/>
</bean>
</beans>
- web.xml配置前端控制器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0">
<!--配置前端控制器-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet< /servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
实现单文件上传
创建多文件上传页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/file/singleFile" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/><br/>
文件上传:<input type="file" name="file"/><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
- 操作成功页面:ok.jsp(我就不列举出来了)
创建页面跳转控制器
@Controller
@RequestMapping("/page")
public class PageController {
@RequestMapping("/single")
public String showSingleFile(){
return "singlefile";
}
@RequestMapping("/ok")
public String showOK(){
return "ok";
}
}
实现文件上传
@Controller
@RequestMapping("/file")
public class FileUploadController {
// 处理单个文件上传
@RequestMapping("/singleFile")
public String singleFile(MultipartFile file, String username, HttpServletRequest request){
String fileName = UUID.randomUUID().toString()+file.getOriginalFilename().substring (file.getOriginalFilename().lastIndexOf("."));
String realPath = request.getServletContext().getRealPath("/fileupload");
File temp = new File(realPath,fileName);
try{
file.transferTo(temp);
}catch(Exception e){
e.printStackTrace();
}
return "redirect:/page/ok";
}
}
注意:
- 在文件上传时,MultipartFile参数的名称需要与页面的 file 组件的 name 相 同
- 如果不同需要使用@RequestParam 注解来指定。
实现多文件上传
创建多文件上传页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/file/multiFile" method="post" enctype="multipart/form-data">
用户名:<input type="text" name="username"/><br/>
文件上传 1:<input type="file" name="file"/><br/>
文件上传 2:<input type="file" name="file"/><br/>
<input type="submit" value="OK"/>
</form>
</body>
</html>
创建页面跳转方法
@RequestMapping("/multifile")
public String showMultiFile(){
return "multifile";
}
实现多文件上传
@RequestMapping("/multiFile")
public String multiFile(MultipartFile file[],String username,HttpServletRequest request){
for(MultipartFile temp:file){
String fileName = UUID.randomUUID().toString()+temp.getOriginalFilename().substring (temp.getOriginalFilename().lastIndexOf("."));
File f = new File(request.getServletContext().getRealPath("/fileupload"),fileName);
try{
temp.transferTo(f);
}catch(Exception e){
e.printStackTrace();
}
}
return "redirect:/page/ok";
}
文件下载
创建下载页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:forEach items="${files}" var="file">
<a href="/file/fileDown?fileName=${file}">${file}</a><br/>
</c:forEach>
</body>
</html>
创建跳转下载页面方法
@RequestMapping("/showFileDown")
public String showFileDown(HttpServletRequest request,Model model){
String realPath = request.getServletContext().getRealPath("/fileupload");
File file = new File(realPath);
String[] arr = file.list();
model.addAttribute("files",arr);
return "filedown";
}
创建文件下载控制器
@RequestMapping("/fileDown")
public void fileDown(String fileName, HttpServletRequest request, HttpServletResponse response){
//设置响应头
response.setHeader("Content-Disposition","attachment;filename="+fileName);
//获取绝对路径
String realPath = request.getServletContext().getRealPath("/fileupload");
File file = new File(realPath,fileName);
//获取字节输出流
try{
ServletOutputStream outputStream = response.getOutputStream();
//读文件
outputStream.write(FileUtils.readFileToByteArray(file));
outputStream.flush();
outputStream.close();
}catch(Exception e){
e.printStackTrace();
}
}