springmvc(三)
Spring MVC上传
Spring MVC为文件上传提供了直接的支持,这种支持是用即插即用的MultipartResolver实现的。SpringMVC使用Apache Commons FileUpload技术实现了一个MultipartResolver实现类:CommonsMultipartResolver。因此,Spring MVC的文件上传还需要依赖于Apache Commons FileUpload的组件。
步骤:
(1) 在mvc配置文件中加入org.springframework.web.multipart.commons.CommonsMultipartResolver
(2) 上传文件会被转成MultipartFile对象。
(3) 调用对象的transferTo方法将文件写出(方式一:标量接收;方式二:对象接收)
Spring MVC下载
文件下载,直接在页面给出一个超链接,该链接href的属性等于要下载文件的文件名,就可以实现文件下载了。但是如果该文件的文件名为中文文件名,在某些早期的浏览器上就会导致下载失败,如果使用最新的Firefox、Opera、Chrome、Safari都可以正常下载文件名为中文的文件了。
Spring MVC提供了一个ResponseEntity类型,可以很方便的定义返回的HttpHeaders和HttpStatus。
注意:
springmvc将http的头信息,状态码等都封装成了对象。
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
下载的方法是:
ResponseEntity(T body, MultiValueMap<String,String> headers, HttpStatus statusCode)
创建web工程,导包
配置web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>文件上传下载</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <!-- 设置springmvc前端控制器 --> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 指定路径解析配置文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <!-- 映射拦截 --> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>*.jspx</url-pattern> </servlet-mapping> <!-- 过滤器,过滤所有的请求设置字符编码 --> <filter> <filter-name>characterEncodingFilter</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <init-param> <param-name>encoding</param-name> <param-value>UTF-8</param-value> </init-param> </filter> <filter-mapping> <filter-name>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
配置springmvc-config.xml文件
<?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:p="http://www.springframework.org/schema/p" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd"> <!-- spring可以自动去扫描base-pack下面的包或者子包下面的java文件, 如果扫描到有Spring的相关注解的类,则把这些类注册为Spring的bean --> <context:component-scan base-package="org.fkit.controller"/> <mvc:annotation-driven/> <mvc:default-servlet-handler/> <!-- 视图解析器 --> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前缀 --> <property name="prefix"> <value>/WEB-INF/content/</value> </property> <!-- 后缀 --> <property name="suffix"> <value>.jsp</value> </property> </bean> <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver"> <!-- 上传文件大小上限,单位为字节(10MB) --> <property name="maxUploadSize"> <value>10485760</value> </property> <!-- 请求的编码格式,必须和jSP的pageEncoding属性一致,以便正确读取表单的内容,默认为ISO-8859-1 --> <property name="defaultEncoding"> <value>UTF-8</value> </property> </bean> </beans>
index.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="uploadForm.jspx">文件上传测试</a><br><br> <a href="registerForm.jspx">用户注册</a><br><br> </body> </html>
在org.fkit.controller包下创建
package org.fkit.controller; import java.io.File; import javax.servlet.http.HttpServletRequest; import org.apache.commons.io.FileUtils; import org.fkit.domain.User; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.http.ResponseEntity; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.multipart.MultipartFile; @Controller//声明该类为控制器 public class FileUploadController { @RequestMapping(value="/uploadForm.jspx")//映射对应index.jsp的请求 public String loginForm(){ //返回uploadForm.jsp页面,前缀和后缀在springmvc-config.xml中配置 return "uploadForm"; } //方式二,使用上传文件封装到对象中 @RequestMapping(value="/registerForm.jspx") public String registerForm(){ return "registerForm"; } //上传文件会自动绑定到MultipartFile中 @RequestMapping(value="/upload.jspx",method=RequestMethod.POST) public String upload(HttpServletRequest request, String description, MultipartFile file) throws Exception{ System.out.println(description); //如果文件不为空,写入上传路径 if(!file.isEmpty()){ //上传文件路径 String path = request.getServletContext().getRealPath("/images"); System.out.println(path); //上传文件名 String filename = file.getOriginalFilename(); //将上传文件保存到一个目标文件当中 File.separator表示“/” 反斜杠 file.transferTo(new File(path+File.separator+filename)); return "success"; }else{ return "error"; } } //方式二,使用对象接收 @RequestMapping(value="/register.jspx") public String register(HttpServletRequest request, User user, Model model)throws Exception{ System.out.println(user.getUsername()); //如果文件不为空,写入上传路径 if(!user.getImage().isEmpty()){ String path = request.getServletContext().getRealPath("/images"); System.out.println(path); //上传文件名 String filename = user.getImage().getOriginalFilename(); //将上传文件保存到一个目标文件当中 user.getImage().transferTo(new File(path+File.separator+filename)); //将用户添加到model model.addAttribute("user", user); return "userInfo";//文件下载 }else{ return "error"; } }
Spring Mvc下载 //<a href="download.jspx?filename= "> @RequestMapping(value="/download.jspx") public ResponseEntity<byte[]> download( HttpServletRequest request, String filename, Model model)throws Exception{ //下载文件路径 String path = request.getServletContext().getRealPath("/images"); File file = new File(path+File.separator+filename); //下载显示的文件名,解决中文名乱码问题 String downloadFileName = new String(filename.getBytes("UTF-8"),"iso-8859-1"); //spring中封装的http头信息对象 HttpHeaders headers = new HttpHeaders(); //通知浏览器以attachment(附件下载方式)打开图片 headers.setContentDispositionFormData("attachment", downloadFileName); /** * response.setContentType("application/octet-stream"); 二进制流 * */ // application/octet-stream : 二进制流数据(最常见的文件下载)。 headers.setContentType(MediaType.APPLICATION_OCTET_STREAM); //读取下载文件返回二进制对象 byte[] body = FileUtils.readFileToByteArray(file); // 201 HttpStatus.CREATED 请求成功并且服务器创建了新的资源。 HttpStatus statusCode = HttpStatus.CREATED; /** * new ResponseEntity<byte[]>(下载的字节文件,http头信息,http状态码) * */ return new ResponseEntity<byte[]>(body, headers, statusCode); } }
对应content文件下的页面信息
success.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> 上传文件成功! </body> </html>
error.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> 上传文件失败! </body> </html>
registerForm.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> <h2>用户注册</h2> <form action="register.jspx" enctype="multipart/form-data" method="post"> <table> <tr> <td>用户名:</td> <td><input type="text" name="username"></td> </tr> <tr> <td>请上传头像:</td> <td><input type="file" name="image"></td> </tr> <tr> <td><input type="submit" value="注册"></td> </tr> </table> </form> </body> </html>
uploadForm.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> <h2>文件上传</h2> <form action="upload.jspx" enctype="multipart/form-data" method="post"> <table> <tr> <td>文件描述:</td> <td><input type="text" name="description"></td> </tr> <tr> <td>请选择文件:</td> <td><input type="file" name="file"></td> </tr> <tr> <td><input type="submit" value="上传"></td> </tr> </table> </form> </body> </html>
userInfo.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> <h3>文件下载</h3> <a href="download.jspx?filename=${requestScope.user.image.originalFilename}"> ${requestScope.user.image.originalFilename } </a> </body> </html>