需要准备的工具和框架

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

文件结构如下

设置依赖包

 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.gome.springmvc</groupId>
<artifactId>Spring4MVCFileDownloadExample</artifactId>
<packaging>war</packaging>
<version>1.0.0</version>
<name>Spring4MVCFileDownloadExample Maven Webapp</name> <properties>
<springframework.version>4.2.0.RELEASE</springframework.version>
</properties> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springframework.version}</version>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies> <build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.4</version>
<configuration>
<warSourceDirectory>src/main/webapp</warSourceDirectory>
<warName>Spring4MVCFileDownloadExample</warName>
<failOnMissingWebXml>false</failOnMissingWebXml>
</configuration>
</plugin>
</plugins>
</pluginManagement> <finalName>Spring4MVCFileDownloadExample</finalName>
</build>
</project>

controller实现

package com.gome.springmvc.controller;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLConnection;
import java.nio.charset.Charset; import javax.servlet.http.HttpServletResponse; import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.FileCopyUtils;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; @Controller
public class FileDownloadController { private static final String INTERNAL_FILE="irregular-verbs-list.pdf";
private static final String EXTERNAL_FILE_PATH="C:/mytemp/SpringMVCHibernateManyToManyCRUDExample.zip"; @RequestMapping(value={"/","/welcome"}, method = RequestMethod.GET)
public String getHomePage(ModelMap model) {
return "welcome";
} /*
* Download a file from
* - inside project, located in resources folder.
* - outside project, located in File system somewhere.
*/
@RequestMapping(value="/download/{type}", method = RequestMethod.GET)
public void downloadFile(HttpServletResponse response, @PathVariable("type") String type) throws IOException { File file = null; if(type.equalsIgnoreCase("internal")){
ClassLoader classloader = Thread.currentThread().getContextClassLoader();
file = new File(classloader.getResource(INTERNAL_FILE).getFile());
}else{
file = new File(EXTERNAL_FILE_PATH);
} if(!file.exists()){
String errorMessage = "Sorry. The file you are looking for does not exist";
System.out.println(errorMessage);
OutputStream outputStream = response.getOutputStream();
outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
outputStream.close();
return;
} String mimeType= URLConnection.guessContentTypeFromName(file.getName());
if(mimeType==null){
System.out.println("mimetype is not detectable, will take default");
mimeType = "application/octet-stream";
} System.out.println("mimetype : "+mimeType); response.setContentType(mimeType); /* "Content-Disposition : inline" will show viewable types [like images/text/pdf/anything viewable by browser] right on browser
while others(zip e.g) will be directly downloaded [may provide save as popup, based on your browser setting.]*/
response.setHeader("Content-Disposition", String.format("inline; filename=\"" + file.getName() +"\"")); /* "Content-Disposition : attachment" will be directly download, may provide save as popup, based on your browser setting*/
//response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName())); response.setContentLength((int)file.length()); InputStream inputStream = new BufferedInputStream(new FileInputStream(file)); //Copy bytes from source to destination(outputstream in this example), closes both streams.
FileCopyUtils.copy(inputStream, response.getOutputStream());
} }

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

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. checked Exception和unchecked exception

    checked Exception: io,sql等exception,程序无法控制的 unchecked exception: 包括Error与RuntimeException及其子类,如:OutO ...

  2. 2016.04.28,英语,《Vocabulary Builder》Unit 20

    nom, comes from the Latin word for 'name'. nominee is 'named', [ˌnɑːmɪ'niː] n. 被提名的人, 名义人. binomial ...

  3. [Zz] DX depth buffer

    声明:本文完全翻译自DX SDK Documentation depth buffer,通常被称为z-buffer或者w-buffer,是设备的一个属性,用来存储深度信息,被D3D使用.当D3D渲染一 ...

  4. 浏览器 user-agent 字符串的故事

    你是否好奇标识浏览器身份的User-Agent,为什么每个浏览器都有Mozilla字样? 故事还得从头说起,最初的主角叫NCSA Mosaic,简称Mosaic(马赛克),是1992年末位于伊利诺伊大 ...

  5. Yii源码阅读笔记(十八)

    View中的查找视图文件方法和渲染文件方法 /** * Finds the view file based on the given view name. * 通过view文件名查找view文件 * ...

  6. Bootstrap页面布局15 - BS带下拉菜单的按钮

    带下拉菜单的按钮 <div class='btn-toolbar'> <div class='btn-group'> <a href='javascript:;' cla ...

  7. pointer

    https://en.wikipedia.org/wiki/Pointer_(computer_programming) In computer science, a pointer is a pro ...

  8. DML以及DQL的使用方法

    DML:数据操作语言 1.插入insert into 单行插入:insert into 表名 (字段名, 字段名,...) values (值, 值, ...) 注:值列表要和字段列表相匹配. ins ...

  9. jq窗口类小问题

    if ($(window).height() + $(window).scrollTop() >= $(document.body).height() - options.marginBotto ...

  10. 异常处理与MiniDump详解(4) MiniDump

    http://blog.csdn.net/vagrxie/article/details/4398721 异常处理与MiniDump详解(4) MiniDump 分类:             [Wi ...