【Spring MVC】文件上传、文件下载

页面效果:
在这里插入图片描述

一、文件下载

1.访问资源时相应头如果没有设置 Content-Disposition,浏览器默认按照 inline 值进行处理
1.1 inline 能显示就显示,不能显示就下载.

2.只需要修改响应头中 Context-Disposition=”attachment;filename=文件名”
2.1 attachment 下载,以附件形式下载.
2.2 filename=值就是下载时显示的下载文件名

3.实现步骤
3.1 导入apache 的两个jar
在这里插入图片描述
3.2 在 jsp 中添加超链接,设置要下载文件

<a href="download?fileName=a.rar">下载</a>

3.2.1 在 springmvc.xml 中放行静态资源 files 文件夹

	<!-- 静态资源 -->
	<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
	<mvc:resources location="/files/" mapping="/files/**"></mvc:resources>

3.3 编写控制器方法

Java示例

@Controller
public class DemoDownload {
	@RequestMapping("download")
	public void download(String filename, HttpServletResponse res, HttpServletRequest req) throws IOException {
		// 设置响应流中文件进行下载
		// attachment是以附件的形式下载,inline是浏览器打开
		// bbb.txt是下载时显示的文件名
		res.setHeader("Content-Disposition", "attachment;filename=bbb.txt"); // 下载
//		res.setHeader("Content-Disposition", "inline;filename=bbb.txt"); // 浏览器打开
		// 把二进制流放入到响应体中
		ServletOutputStream os = res.getOutputStream();
		System.out.println("here download");
		String path = req.getServletContext().getRealPath("files");
		System.out.println("path is: " + path);
		System.out.println("fileName is: " + filename);
		File file = new File(path, filename);
		byte[] bytes = FileUtils.readFileToByteArray(file);
		os.write(bytes);
		os.flush();
		os.close();
	}
}

JSP示例

<a href="download?filename=a.txt">点击下载</a><br/>

二、文件上传

1. 基于apache 的commons-fileupload.jar 完成文件上传.

2. MultipartResovler 作用:
2.1 把客户端上传的文件流转换成MutipartFile 封装类.
2.2 通过MutipartFile 封装类获取到文件流

3. 表单数据类型分类
3.1 在的enctype 属性控制表单类型
3.2 默认值 application/x-www-form-urlencoded,普通表单数据.(少量文字信息)
3.3 text/plain 大文字量时使用的类型.邮件,论文
3.4 multipart/form-data 表单中包含二进制文件内容.(重要)

4. 实现步骤:
4.1 导入springmvc 包和apache 文件上传 commons-fileupload 和 commons-io 两个jar
4.2 编写JSP 页面

<h3>文件上传</h3>
<form action="upload" enctype="multipart/form-data" method="post">
	姓名:<input type="text" name="name"/><br/>
	文件:<input type="file" name="file"/><br/>
	<input type="submit" value="提交"/>
</form>

4.3 配置 springmvc.xml

	<!-- MultipartResovler解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置文件最大字节数 -->
		<property name="maxUploadSize" value="1024"></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>

4.4 编写控制器类
4.4.1 MultipartFile 对象名必须和的name 属性值相同

@Controller
public class DemoUpload {
	@RequestMapping("upload")
	public String upload(MultipartFile file,String name) throws IOException{
		String fileName = file.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));
		// 限制上传文件类型
		if(suffix.equalsIgnoreCase(".png")||suffix.equalsIgnoreCase(".txt")){
			String uuid = UUID.randomUUID().toString();
			FileUtils.copyInputStreamToFile(file.getInputStream(), new File("C:/picture/"+uuid+suffix));
			return "index.jsp";
		}else{
			return "error.jsp";
		}
	}
}

附:springmvc.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: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="cn.hanquan.controller"></context:component-scan>

	<!-- 注解驱动,相当于配置了以下两个类 -->
	<!-- org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping -->
	<!-- org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter -->
	<mvc:annotation-driven></mvc:annotation-driven>

	<!-- 放行静态资源 -->
	<!-- 访问示例:http://localhost:8080/springmvc_test/test/jquery.js -->
	<mvc:resources location="/js/" mapping="/test/**"></mvc:resources>

	<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
	<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
	<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
	<mvc:resources location="/images/" mapping="/files/**"></mvc:resources>

		
	<!-- MultipartResovler解析器 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<!-- 设置文件最大字节数 -->
		<property name="maxUploadSize" value="1024"></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>
	
	<!-- 自定义视图解析器 -->
	<!-- 当跳转语句添加前缀(比如forward:)时,自定义视图解析器无效,走默认视图解析器 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 添加前缀后,写相对路径不用加/ -->
		<property name="prefix" value="/"></property>
		<!-- 后缀没配,与不写相同,可以配成jsp -->
		<property name="suffix" value=""></property>
	</bean>
</beans>

附:web.xml 完整配置

<?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>abc</servlet-name>
		<!-- servlet分发器 -->
		<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>abc</servlet-name>
		<!-- '/'表示除了jsp都拦截 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	
	<!-- 字符编码过滤器 -->
	<!-- 配置文件无关顺序问题,加载时就被实例化,等待tomcat回调 -->
	<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>

附:文件目录结构

在这里插入图片描述

发布了574 篇原创文章 · 获赞 203 · 访问量 19万+

猜你喜欢

转载自blog.csdn.net/sinat_42483341/article/details/104076360
今日推荐