首先在WEB-INF下创建文件夹download,在download文件夹下放入被下载的文件,在HTTP访问时Controller附带上文件名称即可。
例如:…/download?fileName=jQuery.txt
前端JS部分:
<script type="text/javascript">
$(document).ready(function(){
$("#load").click(function(){
//点击下载按钮时,调用downLoad()方法,访问后台,实现下载
downLoad('${pageContext.request.contextPath }/download/download','jQuery.txt');
});
});
/*
JS实现文件下载:
利用jQuary绘制一个隐藏表单
表单里只有一个hidden隐藏域,域的value为文件名
绘制完毕后自动提交,访问后台Controller,实现文件下载
参数:
fromAction:要提交的URL路径
fileName:要下载的文件名称
例如:fromAction:'${pageContext.request.contextPath }/download/download'
fileName :'jQuery.txt'
*/
function downLoad(fromAction,fileName) {
var form = $("<form>"); //定义一个form表单
form.attr('style', 'display:none'); //在form表单中添加查询参数
form.attr('target', '');
form.attr('method', 'post');
form.attr('action', fromAction+'');
var input1 = $('<input>');
input1.attr('type', 'hidden');
input1.attr('name', 'fileName');
input1.attr('value', fileName+'');
//将内置表单添加在页面中
$('body').append(form);
//将隐藏域添加到表单上
form.append(input1);
form.submit();
}
</script>
后台Controller:
/**
* @author 佳。
* @date 2016年3月7日
* @Description: 文件下载
* @param: @param fileName 文件名称
* @return String 返回值为null
* @throws
*/
@RequestMapping("download")
public void download(String fileName, HttpServletRequest request,
HttpServletResponse response) {
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
try {
// /WEB-INF/download文件夹的根目录
String path = request.getSession().
getServletContext().getRealPath("/WEB-INF/download");
// 获取相应文件的流
// File.separator(Windows系统为'/')
InputStream inputStream = new FileInputStream(new File(path
+ File.separator + fileName));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 释放资源
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}