页面效果:

一、文件下载

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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!-- 扫描注解 --><context:component-scanbase-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>

附:文件目录结构

【Spring MVC】文件上传、文件下载相关推荐

  1. Spring MVC 文件上传 文件下载

    索引: 目录索引 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadController.java Files_Ut ...

  2. spring mvc文件上传小例子

    spring mvc文件上传小例子 1.jsp页面 <%@page contentType="text/html;charset=UTF-8"%> <%@page ...

  3. Spring MVC文件上传示例教程 - 单个和多个文件

    Spring MVC文件上传示例教程 - 单个和多个文件 文件上传是任何Web应用程序中非常常见的任务.我们之前已经看过如何在Servlet和Struts2文件上传中上传文件.今天我们将学习Sprin ...

  4. spring mvc文件上传与下载

    基于spring mvc注解: (1)导入jar包:ant.jar.commons-fileupload.jar.connom-io.jar. (2)在spring-mvc.xml中的配置 <! ...

  5. Spring MVC文件上传

    1.配置xml文件 1 <!-- 指定文件上传解析 名字不能乱给 --> 2 <bean name="multipartResolver" class=" ...

  6. 【Spring】Spring MVC文件上传--整合bootstrap-fileinput和jQuery-File-Upload

    前言 这里分享两个使用Spring MVC进行文件上传的简单示例, 分别整合bootstrap-fileinput 和 Jquery File Upload , 代码十分简单, 都是入门的示例,因此这 ...

  7. Springmvc,Spring MVC文件上传

    Springmvc文件上传: 1.代码截图如下: 2.UploadController.java: package cn.csdn.controller;import java.io.File;imp ...

  8. Spring MVC文件上传下载实例

    工程目录: 导入jar: controllers.FileControler.java package controllers;import java.io.File; import java.io. ...

  9. Spring mvc 文件上传

    1.文件上传的必要前提 A.form 表单的 enctype 取值必须是:multipart/form-data (默认值是:application/x-www-form-urlencoded) en ...

  10. spring mvc 文件上传 form表单

    jsp页面 <form class="form-horizontal" role="form" id="form" enctype=& ...

最新文章

  1. Python实现向s3共享存储上传和下载文件
  2. oracle rac 磁盘重建,Oracle RAC环境下重建ASM磁盘组 Re-create ASM diskgroup with Oracle RAC...
  3. 【Linux】ps命令
  4. 理解CSS3 transform中的Matrix(矩阵)
  5. 用Java实现天天酷跑(附源码),只能用牛逼来形容了!
  6. Python rjust() 方法
  7. 【视频编解码的新挑战与新机会】
  8. WPF Image Source 设置相对路径图片
  9. itextpdf添加表格元素_java使用iText生成pdf表格详解
  10. 做 局域网聊天 的人越来越多了
  11. 如何从程序员转型为项目经理
  12. Promises 对比 callbacks
  13. Windows phone应用开发[15]-辅助工具
  14. keras搭建多层LSTM
  15. Spring3之InternalResourceViewResolver
  16. 大数据知识点汇总---Redis,Spark,Kafka,Hive,Mysql,Hbase,Hadoop...
  17. IC卡防批量复制破解 Mifare卡一卡一密方案说明 门禁卡校园卡水卡会员卡防破解方案
  18. git 拉取代码库的项目到本地(window系统)
  19. 常州大学 计算机与人工智能学院,常熟理工学院新闻网
  20. Excel 宏 将工作表中的数据按照顺序分拆到 本工作簿 的其他工作表

热门文章

  1. js检测鼠标是否在操作_原生JS趣味demo:炫酷头像鼠标追随效果的实现
  2. python turtle库画椭圆_如何用Python画一只肥肥的柯基狗狗——turtle库绘制椭圆与弧线实践...
  3. GitPages个人域名博客
  4. 梅州有学java的地方吗,梅州java工资水平,梅州java工资很高吗,梅州java工资底薪能到多少...
  5. jsoncpp和rapidjson哪个好用?
  6. setiosflags(ios::fixed)和setprecision()
  7. 如何制作出让女朋友满意的大片
  8. 高级数据结构与算法 | 二叉搜索树(Binary Search Tree)
  9. springcloud 2.0 服务链路追踪踩坑以及一些小小的理解
  10. 区间调度之区间交集问题