1、文件的上传下载及环境配置所需包:
2、配置文件–SpringMVC
文件上传解析器(MultipartResolver):对上传的文件的相关属性信息进行配置(例如:大小),文件解析器类对象是在spring-web-xxx.jar包下:
;
异常解析器(ExceptionResolver)–org.springframework.web.servlet.handler.SimpleMappingExceptionResolver,可以通过配置属性exceptionMappings,配置实际异常类,当触发该异常时,跳转到配置的对应页面中,此处配置了异常–org.springframework.web.multipart.MaxUploadSizeExceededException,该异常是在spring-web-xxx.jar下,异常解析器对象类是在包spring-webmvc-xxx.jar下:
<?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: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.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="Controller"></context:component-scan>
<!--注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
<!--放行的静态文件-->
<mvc:resources mapping="/files/**" location="/files/"></mvc:resources>
<!--文件上传解析器配置-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<property name="maxUploadSize" value="1073741824"></property>
</bean>
<!--异常解析器-->
<bean id="exceptionResolver" class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
<property name="exceptionMappings">
<props>
<prop key="org.springframework.web.multipart.MaxUploadSizeExceededException">/error.jsp</prop>
</props>
</property>
</bean>
</beans>
3、web.xml文件配置:
web.xml文件配置与以往一致主要配置了SpringMVC的前端控制器 和 字符编码过滤。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
<!--前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</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>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!---->
<filter>
<filter-name>encoding</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>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
4、控制器类:
4.1、Demo01请求–文件下载:
参数:String fileName, HttpServletResponse rep,HttpServletRequest req
其中fileName是页面传值要下载的文件名称,页面参数名称要与此处参数名称一致。
方法体:设置下载的响应头–rep.setHeader(“Content-Disposition”,“attachment;fileName=”+fileName);
此处fileName是设置下载后的文件命名,可以和传参名称一致,自定义下载后的文件名称;
查找文件存放的路径–req.getServletContext().getRealPath(“files”);
使用New File(path,fileName)根据获取的文件存放路径 和 需要下载的文件名称获取文件;
使用commons-io.jar包中的FileUtils类转换文件为字节码,存入到字节数组中,byte[] bytes = FileUtils.readFileToByteArray(file);
使用HttpServletResponse中的文件输出流getOutputStream()方法,将文件写入到客户端:
out.write(bytes);
out.flush();
out.close();
4.2、文件上传:
Demo02上传方法参数:MultipartFile fileName,String name,HttpServletRequest req
MultipartFile fileName:将上传的文件分装成MultipartFile ;
通过方法fileName.getOriginalFilename() 获取文件名称,然后使用方法–filena.substring(filena.lastIndexOf("."))获取文件扩展名,可以使用此扩展名限制上传文件的类型;
最重要的是使用包commons-io.jar包中的FileUtils. copyInputStreamToFile将文件写入到指定路径下 ----- FileUtils.copyInputStreamToFile(fileName.getInputStream(),new File(path+"/"+str+suf));
package Controller;
import org.apache.commons.io.FileUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
@Controller
public class downloadController {
@RequestMapping("Demo01")
@ResponseBody
public void Demo01ForDownload(String fileName, HttpServletResponse rep,HttpServletRequest req) throws IOException {
//设置响应头文件下载,fileName是下载下来的文件名(可以自定义)
rep.setHeader("Content-Disposition","attachment;fileName="+fileName);
//
OutputStream out = rep.getOutputStream(); //文件输出流
String path = req.getServletContext().getRealPath("files"); //查找存放文件的文件夹路径
File file = new File(path,fileName);
byte[] bytes = FileUtils.readFileToByteArray(file);
out.write(bytes);
out.flush();
out.close();
}
@RequestMapping("Demo02")
public String Demo02(MultipartFile fileName,String name,HttpServletRequest req) throws IOException {
String filena = fileName.getOriginalFilename();
String suf = filena.substring(filena.lastIndexOf(".")); //开始剪切的位置,包头不包尾
String str = System.currentTimeMillis()+"";
String path = req.getServletContext().getRealPath("files");
System.out.println("path : "+path);
if(suf.equalsIgnoreCase(".jpg")){
FileUtils.copyInputStreamToFile(fileName.getInputStream(),new File(path+"/"+str+suf));
return "/index.jsp";
}else{
return "error.jsp";
}
}
}
5、页面—index.jsp
<%@page contentType="text/html; utf-8" language="java" pageEncoding="UTF-8" %>
<html>
<body>
<h2>文件下载</h2>
<hr>
<a href="Demo01?fileName=abc.txt">下载</a>
<hr>
<!--附件上传需要在form中注明属性enctype="multipart/form-data",此属性不影响基本文本类型提交-->
<form action="Demo02" method="post" enctype="multipart/form-data">
文件名称:<input type="text" name="name" style="text-align: left;">
附件:<input type="file" name="fileName">
<input type="submit" value="提交按钮">
</form>
<hr>
<button>注:form表单提交附件(上传文件)需要设置属性值:enctype="multipart/form-data",此属性值不影响form表单中的基本文本数据提交</button>
</body>
</html>
error.jsp(发生异常时跳转页面):
<%--
Created by IntelliJ IDEA.
User: xingfuhu
Date: 2020/5/27
Time: 0:04
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>异常跳转页面</title>
</head>
<body>
Error.jsp---请排查异常出现原因!!!!!
</body>
</html>