java服务器文件下载到本地

版权声明:支持原创,注明出处。 https://blog.csdn.net/qq_38584967/article/details/83050772

前言

我实现了一个生成excel的功能,让用户在访问服务器点击导出按钮时下载到用户本地。这就不能只是简单的java io写出了,总不能写出到服务器本地了吧,用户本地一脸懵逼。怎么返回文件给访问网页的用户?通过response返回文件数据。

正文

逻辑是:用户点击按钮—>前台提交—>后台处理—>返回文件
首先我们前台需要一个from表单提交事件

 <form id="dailyCountThree" method="post" 
 	action="exportexcellist.action?cmd=function" >
 	...
</form>

作用就是点击按钮后跳转到指定action方法,在action完成生成文件的处理之后呢,将文件想办法通过respone给返回回去。

//即将下载的文件名字
String filename =  fileName + time + ".xls";
//将文件名字编码
filename = URLEncoder.encode(filename,"UTF-8");
//拿到当前respone,很关键
HttpServletResponse response = 
((ServletRequestAttributes)RequestContextHolder.getRequestAttributes()).getResponse();
//通过response得到输出流
OutputStream os=response.getOutputStream();
//清除缓冲区中存在的任何数据以及状态代码和标头
response.reset();
response.setContentType("application/x-download");
// 设定输出文件头
response.addHeader("Content-Disposition","attachment;filename=" + filename);
// 定义输出类型
response.setContentType("application/msexcel");
//通过response得到的输出流os将文件输出
os.write(...)

这里需要注意的是response.reset()方法,介绍如下:

Clears any data that exists in the buffer as well as the status code and headers.
If the response has been committed, this method throws an IllegalStateException.
清除缓冲区中存在的任何数据以及状态代码和标头。
如果响应已提交,则此方法引发IllegalStateException异常。

部分内容参考
Java 从服务器下载文件到本地

猜你喜欢

转载自blog.csdn.net/qq_38584967/article/details/83050772