需要准备的工具和框架

  • Spring 4.2.0.RELEASE
  • Bootstrap v3.3.2
  • Maven 3
  • JDK 1.7
  • Tomcat 8.0.21
  • Eclipse JUNO Service Release 2

文件结构如下

设置依赖包

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2. xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3. <modelVersion>4.0.0</modelVersion>
  4. <groupId>com.gome.springmvc</groupId>
  5. <artifactId>Spring4MVCFileDownloadExample</artifactId>
  6. <packaging>war</packaging>
  7. <version>1.0.0</version>
  8. <name>Spring4MVCFileDownloadExample Maven Webapp</name>
  9.  
  10. <properties>
  11. <springframework.version>4.2.0.RELEASE</springframework.version>
  12. </properties>
  13.  
  14. <dependencies>
  15. <dependency>
  16. <groupId>org.springframework</groupId>
  17. <artifactId>spring-webmvc</artifactId>
  18. <version>${springframework.version}</version>
  19. </dependency>
  20.  
  21. <dependency>
  22. <groupId>javax.servlet</groupId>
  23. <artifactId>javax.servlet-api</artifactId>
  24. <version>3.1.0</version>
  25. </dependency>
  26. <dependency>
  27. <groupId>javax.servlet</groupId>
  28. <artifactId>jstl</artifactId>
  29. <version>1.2</version>
  30. </dependency>
  31. </dependencies>
  32.  
  33. <build>
  34. <pluginManagement>
  35. <plugins>
  36. <plugin>
  37. <groupId>org.apache.maven.plugins</groupId>
  38. <artifactId>maven-compiler-plugin</artifactId>
  39. <version>3.2</version>
  40. <configuration>
  41. <source>1.7</source>
  42. <target>1.7</target>
  43. </configuration>
  44. </plugin>
  45. <plugin>
  46. <groupId>org.apache.maven.plugins</groupId>
  47. <artifactId>maven-war-plugin</artifactId>
  48. <version>2.4</version>
  49. <configuration>
  50. <warSourceDirectory>src/main/webapp</warSourceDirectory>
  51. <warName>Spring4MVCFileDownloadExample</warName>
  52. <failOnMissingWebXml>false</failOnMissingWebXml>
  53. </configuration>
  54. </plugin>
  55. </plugins>
  56. </pluginManagement>
  57.  
  58. <finalName>Spring4MVCFileDownloadExample</finalName>
  59. </build>
  60. </project>

controller实现

  1. package com.gome.springmvc.controller;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.File;
  5. import java.io.FileInputStream;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.io.OutputStream;
  9. import java.net.URLConnection;
  10. import java.nio.charset.Charset;
  11.  
  12. import javax.servlet.http.HttpServletResponse;
  13.  
  14. import org.springframework.stereotype.Controller;
  15. import org.springframework.ui.ModelMap;
  16. import org.springframework.util.FileCopyUtils;
  17. import org.springframework.web.bind.annotation.PathVariable;
  18. import org.springframework.web.bind.annotation.RequestMapping;
  19. import org.springframework.web.bind.annotation.RequestMethod;
  20.  
  21. @Controller
  22. public class FileDownloadController {
  23.  
  24. private static final String INTERNAL_FILE="irregular-verbs-list.pdf";
  25. private static final String EXTERNAL_FILE_PATH="C:/mytemp/SpringMVCHibernateManyToManyCRUDExample.zip";
  26.  
  27. @RequestMapping(value={"/","/welcome"}, method = RequestMethod.GET)
  28. public String getHomePage(ModelMap model) {
  29. return "welcome";
  30. }
  31.  
  32. /*
  33. * Download a file from
  34. * - inside project, located in resources folder.
  35. * - outside project, located in File system somewhere.
  36. */
  37. @RequestMapping(value="/download/{type}", method = RequestMethod.GET)
  38. public void downloadFile(HttpServletResponse response, @PathVariable("type") String type) throws IOException {
  39.  
  40. File file = null;
  41.  
  42. if(type.equalsIgnoreCase("internal")){
  43. ClassLoader classloader = Thread.currentThread().getContextClassLoader();
  44. file = new File(classloader.getResource(INTERNAL_FILE).getFile());
  45. }else{
  46. file = new File(EXTERNAL_FILE_PATH);
  47. }
  48.  
  49. if(!file.exists()){
  50. String errorMessage = "Sorry. The file you are looking for does not exist";
  51. System.out.println(errorMessage);
  52. OutputStream outputStream = response.getOutputStream();
  53. outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
  54. outputStream.close();
  55. return;
  56. }
  57.  
  58. String mimeType= URLConnection.guessContentTypeFromName(file.getName());
  59. if(mimeType==null){
  60. System.out.println("mimetype is not detectable, will take default");
  61. mimeType = "application/octet-stream";
  62. }
  63.  
  64. System.out.println("mimetype : "+mimeType);
  65.  
  66. response.setContentType(mimeType);
  67.  
  68. /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser
  69. while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
  70. response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() +"\""));
  71.  
  72. /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
  73. //response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
  74.  
  75. response.setContentLength((int)file.length());
  76.  
  77. InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
  78.  
  79. //Copy bytes from source to destination(outputstream in this example), closes both streams.
  80. FileCopyUtils.copy(inputStream, response.getOutputStream());
  81. }
  82.  
  83. }

文件下载中需要注意的几个问题

1. 文件存储路径应该做混淆,防止从过猜测url等参数尝试获得其他文件

2. 除了对参数校验,还要对将下载的文件绝对路径、类型校验。

3. 白名单策略,只有规定路径下,规定类型、拥有规定权限的人才可以下载。

spring4 文件下载功能的更多相关文章

  1. JAVA文件下载功能问题解决日志

    今天给报告系统做了个下载功能,遇到了挺多问题,通过查资料一一解决了. 1.首先遇到的问题是:java后台的输出流输出之后,没有任何报错,浏览器端不弹出保存文件的对话框,原本是ajax请求到后台的con ...

  2. 解决springmvc中文件下载功能中使用javax.servlet.ServletOutputStream out = response.getOutputStream();后运行出异常但结果正确的问题

    问题描述: 在springmvc中实现文件下载功能一般都会使用javax.servlet.ServletOutputStream out = response.getOutputStream();封装 ...

  3. WebView实现文件下载功能

    WebView控制调用相应的WEB页面进行展示.安卓源码当碰到页面有下载链接的时候,点击上去是一点反应都没有的.原来是因为WebView默认没有开启文件下载的功能,如果要实现文件下载的功能,需要设置W ...

  4. Spring Boot实现文件下载功能

    我们只需要创建一个控制器(Controler)文件,即Controller目录下的File_Download.java,其完整目录如下: @Controller public class File_D ...

  5. Spring Boot入门(11)实现文件下载功能

      在这篇博客中,我们将展示如何在Spring Boot中实现文件的下载功能.   还是遵循笔者写博客的一贯风格,简单又不失详细,实用又能让你学会.   本次建立的Spring Boot项目的主要功能 ...

  6. ASP.NET网页中RAR、DOC、PDF等文件下载功能实例源代码

    以前做asp.net下载功能的时候都是采用:<a href="http://www.wang0214.com/wgcms">下载</a>的方式来实现下载. ...

  7. java web文件下载功能实现 (转)

    http://blog.csdn.net/longshengguoji/article/details/39433307 需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片 两种实现方法: 一 ...

  8. 【Servlet】java web 文件下载功能实现

    需求:实现一个具有文件下载功能的网页,主要下载压缩包和图片 两种实现方法: 一:通过超链接实现下载 在HTML网页中,通过超链接链接到要下载的文件的地址 <!DOCTYPE html> & ...

  9. ASP.NET MVC 向浏览器发送文件以提供文件下载功能

    撑到大三了,结果发现周围的同学更加堕落了,尤其是某些人,表面上看起来很认真,实际上三天打鱼,两天晒网,结果一事无成,却还要抱怨学校教育失败. 为了吸取他们的教训,就算是一个小小的编码问题,我也要努力解 ...

随机推荐

  1. HTTP 笔记与总结(8)HTTP 与内容压缩

    以环球网的一篇新闻为例,抓包图: (Powered-By-ChinaCache:HIT from 060120b3g7.16 表示当前页面不是来自环球网的主服务器,而是来自中国的缓存服务器节点,HIT ...

  2. 采用HSV生成随机颜色

    使用hsv/hsb生成随机颜色,并排除靠近黑白两色的色值 public static String randomColor(){ int max = 25500000 ; Random rand = ...

  3. TeamViewer“试用期已到期”解决方法

    今天打开TeamViewer,显示试用期已到期,不能远程至其它电脑上.软件重装也没用,因为它与你的机器及网卡做了绑定. 查看网上资料,发现需要删除注册信息等操作才能继续使用,步骤如下: 说明:操作前, ...

  4. rsync安装及配置

    一.Server端 CentOS 6下安装yum -y install xinetd1.配置:vi /etc/xinetd.d/rsyncservice rsync{    disable = yes ...

  5. 版本python2和版本3.X的一个区别之一

    print函数 虽然print语法是Python 3中一个很小的改动,且应该已经广为人知,但依然值得提一下:Python 2中的print语句被Python 3中的print()函数取代,这意味着在P ...

  6. nRF51822之模拟IIC

    使用的工程为是基于sdk10工程 在将以nRF51_SDK_10.0.0_dc26b5e\examples\peripheral\twi_sensor作为模版 修改代码main.c #include ...

  7. AppDelegate

    一.基础知识 1) main.m指定了程序的入口点 UIApplicationMain(argc, argv,nil,NSStringFromClass([StartingPointAppDelega ...

  8. HBase HDFS目录树

    一.0.94-cdh4.2.1版本系统级别的一级目录如下,用户自定义的均在这个/hbase 下的一级子目录下/hbase/-ROOT-/hbase/.META./hbase/.archive/hbas ...

  9. ADO.NET连接到数据库(oracle)

    本文摘抄于http://www.cnblogs.com/luluping/archive/2009/10/13/1582737.html,如有侵权,请联系博主. OracleConnection 对象 ...

  10. Windows Runtime - 面向对象化的C++(并非意味着托管)

    Windows 8的开发平台总体上分为两部分:一是全新的WinRT,界面搭配Metro style,二是传统的Win32..NET(SL).IE三大平台,界面为传统窗体风格.其中全新的WinRT被微软 ...