问题描述:在html页面中用“<a href='a.txt'>下载</a>”的形式让用户下载txt文档,浏览器往往是直接在html里面打开txt文档了,而不是我们需要的下载。
一,写一个接口,该接口以流的形式回传txt文档到html页面
下面使用spring mvc作为例子controller
@RequestMapping(value = "/download")
public void download(HtppServletResponse response){
//用result来保存txt文档的内容 ,具体内容请自己写读取流操作
byte[] result = null;
OutputStream os = response.getOutputStream();
try {
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=" + new Date().getTime() + ".txt");
response.setContentType("text/plain; charset=utf-8");
os.write(result);
os.flush();
}
finally {
if (os != null) {
os.close();
}
}
}
在html页面上加上<a href='/download'>下载txt</a>就可以了。这个适合txt文档内容动态生成的情况。
二,利用拦截器修改文件的ContentType
思路:
1,编写一个过滤器filter,拦截所有以.txt结尾的请求。只要该请求是以.txt结尾的,把response的contentType设置为text/plain。
response.setContentType("text/plain; charset=utf-8");
这样子就可以变成下载了。这种情况适合txt文档为事先准备好的固定内容。
如果读者发现可以直接在html设置即可下载的方法,麻烦告知。