<div>
<a href="/Cyberspace/main/downloadFile.do?fileName=模板.xlsx">模板下载</a>
</div>

方案一:

    // 文件下载
@RequestMapping(value = "/downloadFile")
public ResponseEntity<byte[]> downloadFile() throws IOException {
String basePath = "F:/testDir/";
String fileName = "ChromeStandaloneV45.0.2454.101.exe";
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "utf-8"));//这里用URLEncoder.encode是为了解决文件名中的中文乱码问题
return new ResponseEntity<byte[]>(FileUtils.readFileToByteArray(new File(basePath + fileName)), headers, HttpStatus.CREATED);
}

配置xxx-servelt.xml

<bean id="stringHttpMessageConverter" class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8" index="0"></constructor-arg><!-- 避免出现乱码 -->
<property name="supportedMediaTypes">
<list>
<value>text/plain;charset=UTF-8</value>
</list>
</property>
</bean>
<!-- 避免IE出现下载JSON文件的情况 -->
<bean id="mappingJacksonHttpMessageConverter" class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=UTF-8</value>
</list>
</property>
</bean>
<bean id="byteArrayHttpMessageConverter" class="org.springframework.http.converter.ByteArrayHttpMessageConverter" />
<!-- 启动Spring MVC的注解功能,完成请求和注解POJO的映射 -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="byteArrayHttpMessageConverter" />
<ref bean="stringHttpMessageConverter" />
<ref bean="mappingJacksonHttpMessageConverter" /><!-- json转换器 -->
</list>
</property>
</bean>

方案二:通过Response获得输出流,以流的形式下载文件。以下代码大部分是一样的,自行选择

/**
* 文件下载
*
* @param path
* 文件路径(绝对)
* @param response
* 响应对象
*/
public static void download(String path, HttpServletResponse response) {
File file = new File(path);
InputStream fis = null;
OutputStream os = null;
try {
if (!file.exists()) {
response.getWriter().print("文件不存在");
}
// 以流的形式下载文件
fis = new BufferedInputStream(new FileInputStream(file));
// 设置响应报头
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(file.getName(), ENCODING));
response.addHeader("Content-Length", "" + file.length());
response.setContentType(MIME_TYPE_BIN);
response.setCharacterEncoding(ENCODING); // 写入响应流数据
os = new BufferedOutputStream(response.getOutputStream());
byte[] bytes = new byte[1024];
while (fis.read(bytes) != -1) {
os.write(bytes);
}
} catch (Throwable e) {
if (e instanceof ClientAbortException) {
// 浏览器点击取消
LOGGER.info("用户取消下载!");
} else {
e.printStackTrace();
}
} finally {
try {
if (os != null) {
os.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
} }
} /**
* 下载服务器已存在的文件,支持断点续传
*
* @param request
* 请求对象
* @param response
* 响应对象
* @param path
* 文件路径(绝对)
*/
public static void download(HttpServletRequest request, HttpServletResponse response, File proposeFile) {
LOGGER.debug("下载文件路径:" + proposeFile.getPath());
InputStream inputStream = null;
OutputStream bufferOut = null;
try {
// 设置响应报头
long fSize = proposeFile.length();
response.setContentType("application/x-download");
// Content-Disposition: attachment; filename=WebGoat-OWASP_Developer-5.2.zip
response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(proposeFile.getName(), ENCODING));
// Accept-Ranges: bytes
response.setHeader("Accept-Ranges", "bytes");
long pos = 0, last = fSize - 1, sum = 0;// pos开始读取位置; last最后读取位置; sum记录总共已经读取了多少字节
if (null != request.getHeader("Range")) {
// 断点续传
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
try {
// 情景一:RANGE: bytes=2000070- 情景二:RANGE: bytes=2000070-2000970
String numRang = request.getHeader("Range").replaceAll("bytes=", "");
String[] strRange = numRang.split("-");
if (strRange.length == 2) {
pos = Long.parseLong(strRange[0].trim());
last = Long.parseLong(strRange[1].trim());
} else {
pos = Long.parseLong(numRang.replaceAll("-", "").trim());
}
} catch (NumberFormatException e) {
LOGGER.error(request.getHeader("Range") + " is not Number!");
pos = 0;
}
}
long rangLength = last - pos + 1;// 总共需要读取的字节
// Content-Range: bytes 10-1033/304974592
String contentRange = new StringBuffer("bytes ").append(pos).append("-").append(last).append("/").append(fSize).toString();
response.setHeader("Content-Range", contentRange);
// Content-Length: 1024
response.addHeader("Content-Length", String.valueOf(rangLength)); // 跳过已经下载的部分,进行后续下载
bufferOut = new BufferedOutputStream(response.getOutputStream());
inputStream = new BufferedInputStream(new FileInputStream(proposeFile));
inputStream.skip(pos);
byte[] buffer = new byte[1024];
int length = 0;
while (sum < rangLength) {
length = inputStream.read(buffer, 0, ((rangLength - sum) <= buffer.length ? ((int) (rangLength - sum)) : buffer.length));
sum = sum + length;
bufferOut.write(buffer, 0, length);
}
} catch (Throwable e) {
if (e instanceof ClientAbortException) {
// 浏览器点击取消
LOGGER.info("用户取消下载!");
} else {
LOGGER.info("下载文件失败....");
e.printStackTrace();
}
} finally {
try {
if (bufferOut != null) {
bufferOut.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} public static void downloadWithoutEncode(HttpServletRequest request, HttpServletResponse response, File proposeFile) {
LOGGER.debug("下载文件路径:" + proposeFile.getPath());
InputStream inputStream = null;
OutputStream bufferOut = null;
try {
// 设置响应报头
long fSize = proposeFile.length();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment; filename=" + proposeFile.getName());
response.setHeader("Accept-Ranges", "bytes");
long pos = 0, last = fSize - 1, sum = 0;// pos开始读取位置; last最后读取位置; sum记录总共已经读取了多少字节
if (null != request.getHeader("Range")) {
// 断点续传
response.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
try {
// 情景一:RANGE: bytes=2000070- 情景二:RANGE: bytes=2000070-2000970
String numRang = request.getHeader("Range").replaceAll("bytes=", "");
String[] strRange = numRang.split("-");
if (strRange.length == 2) {
pos = Long.parseLong(strRange[0].trim());
last = Long.parseLong(strRange[1].trim());
} else {
pos = Long.parseLong(numRang.replaceAll("-", "").trim());
}
} catch (NumberFormatException e) {
LOGGER.error(request.getHeader("Range") + " is not Number!");
pos = 0;
}
}
long rangLength = last - pos + 1;// 总共需要读取的字节
// Content-Range: bytes 10-1033/304974592
String contentRange = new StringBuffer("bytes ").append(pos).append("-").append(last).append("/").append(fSize).toString();
response.setHeader("Content-Range", contentRange);
// Content-Length: 1024
response.addHeader("Content-Length", String.valueOf(rangLength)); // 跳过已经下载的部分,进行后续下载
bufferOut = new BufferedOutputStream(response.getOutputStream());
inputStream = new BufferedInputStream(new FileInputStream(proposeFile));
inputStream.skip(pos);
byte[] buffer = new byte[1024];
int length = 0;
while (sum < rangLength) {
length = inputStream.read(buffer, 0, ((rangLength - sum) <= buffer.length ? ((int) (rangLength - sum)) : buffer.length));
sum = sum + length;
bufferOut.write(buffer, 0, length);
}
} catch (Throwable e) {
if (e instanceof ClientAbortException) {
// 浏览器点击取消
LOGGER.info("用户取消下载!");
} else {
LOGGER.info("下载文件失败....");
e.printStackTrace();
}
} finally {
try {
if (bufferOut != null) {
bufferOut.close();
}
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* @param path
* 文件路径(绝对)
* @param response
* 响应对象
* @return
*/
public static Boolean download(String path, HttpServletResponse response, String filename) {
Boolean isBoolean = false;
File file = new File(path);
InputStream fis = null;
OutputStream os = null;
try {
if (!file.exists()) {
response.getWriter().print("文件不存在");
}
// 以流的形式下载文件
fis = new BufferedInputStream(new FileInputStream(file));
// 设置响应报头
response.reset();
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename.trim(), ENCODING));
response.addHeader("Content-Length", "" + file.length());
response.setContentType(MIME_TYPE_BIN);
response.setCharacterEncoding(ENCODING);
// 写入响应流数据
os = new BufferedOutputStream(response.getOutputStream());
byte[] bytes = new byte[1024];
while (fis.read(bytes) != -1) {
os.write(bytes);
}
isBoolean = true;
} catch (Throwable e) {
if (e instanceof ClientAbortException) {
// 浏览器点击取消
isBoolean = false;
LOGGER.info("用户取消下载!");
} else {
isBoolean = false;
e.printStackTrace();
}
} finally {
try {
if (os != null) {
os.close();
}
if (fis != null) {
fis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return isBoolean;
}

Spring MVC文件下载的更多相关文章

  1. spring mvc 文件下载 get请求解决中文乱码问题

    方案简写,自己或有些基础的可以看懂,因为没时间写的那么详细 方案1 spring mvc解决get请求中文乱码问题, 在tamcat中server.xml文件 URIEncoding="UT ...

  2. spring mvc 文件下载

    在controller中进行代码编写: @RequestMapping("/download") public ResponseEntity<byte[]> downl ...

  3. Spring MVC 文件下载时候 发现IE不支持

    @RequestMapping("download") public ResponseEntity<byte[]> download(Long fileKey) thr ...

  4. Spring MVC 的文件下载

    在看Spring MVC文件下载之前请先看Spring MVC文件上传 地址:http://www.cnblogs.com/dj-blog/p/7535101.html 文件下载比较简单,在超链接中指 ...

  5. Spring MVC教程——检视阅读

    Spring MVC教程--检视阅读 参考 Spring MVC教程--一点--蓝本 Spring MVC教程--c语言中午网--3.0版本太老了 Spring MVC教程--易百--4.0版本不是通 ...

  6. Spring MVC 文件上传 & 文件下载

    索引: 开源Spring解决方案--lm.solution 参看代码 GitHub: pom.xml WebConfig.java index.jsp upload.jsp FileUploadCon ...

  7. spring mvc的excel报表文件下载时流的冲突解决

    在jsp或者在servlet中有时要用到 response.getOutputStream(),但是此时会在后台报这个错误java.lang.IllegalStateException: getOut ...

  8. Http请求中Content-Type讲解以及在Spring MVC中的应用

    引言: 在Http请求中,我们每天都在使用Content-type来指定不同格式的请求信息,但是却很少有人去全面了解content-type中允许的值有多少,这里将讲解Content-Type的可用值 ...

  9. Spring MVC 学习总结(三)——请求处理方法Action详解

    Spring MVC中每个控制器中可以定义多个请求处理方法,我们把这种请求处理方法简称为Action,每个请求处理方法可以有多个不同的参数,以及一个多种类型的返回结果. 一.Action参数类型 如果 ...

随机推荐

  1. doctype声明、浏览器的标准、怪异等模式

    doctype 标准(严格)模式(Standards Mode).怪异(混杂)模式(Quirks Mode),如何触发,区分他们有何意义? 触发标准模式 1.加DOCTYPE声明,比如:<!DO ...

  2. 【面试题041】和为s的两个数字VS和为s的连续正数序列

    [面试题041]和为s的两个数字VS和为s的连续正数序列 题目一:     输入一个递增排序的数组和一个数字s,在数组中查找两个数,使得它们的和正好是s.如果有多对数字的和等于s,输出任意一对即可. ...

  3. 线性时间常数空间找到数组中数目超过n/5的所有元素

    问题描述: Design an algorithm that, given a list of n elements in an array, finds all the elements that ...

  4. Javascript 偏移量总结

    <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <m ...

  5. mvc5 @RenderSection("scripts", required: false) 什么意思

    在模板中 相当于占位符 使用方法如下 @section scripts{ //coding }

  6. 传说中的WCF(8):玩转消息协定

    Message翻译成中文,相信各位不陌生,是啊,就是消息,在WCF中也有消息这玩意儿,不知道你怎么去理解它.反正俺的理解,就像我们互发短信一个道理,通讯的双方就是服务器与客户端,说白了吧,就是二者之间 ...

  7. poj 3522(最小生成树应用)

    题目链接:http://poj.org/problem?id=3522思路:题目要求最小生成树中最大边与最小边的最小差值,由于数据不是很大,我们可以枚举最小生成树的最小边,然后kruskal求最小生成 ...

  8. Android 核心分析之十二Android GEWS窗口管理之基本架构原理

    Android GWES之窗口管理之基本构架原理 Android的窗口管理是C/S模式的.Android中的Window是表示Top Level等顶级窗口的概念.DecorView是Window的To ...

  9. qt resize() 和 geometry()

    resize(),设置的部件客户区的大小.只有当该部件被show后才生效,即geomery() 返回的才是 resize() 的客户区大小.

  10. c++ 字符串函数用法举例

    1. substr() 2. replace() 例子:split() 字符串切割: substr 函数原型: , size_t n = npos ) const; 解释:抽取字符串中从pos(默认为 ...