ajax方式下载文件,比如txt、 word、 pdf、 jpg等,不需要在页面直接打开,实现异步下载,不刷新当前页面。
1.首先点击下载按钮,把所需要下载的参数,比如说下载地址,或者服务器可以检索出来的地址参数取得。
页面:
<a id="mac_summary_download_btn" class="btn btn-sm btn-default" target="_self" href="javascript:void(0)"> <span class="glyphicon glyphicon-download-alt"></span> 下载 </a>
2.需要访问的下载地址action。
//下载事件
$("#mac_summary_download_btn").click(function(){
ROOF.Utils.showBlock();
var trs = table.getSelectedTrNoClone();
if (trs.length == 0 || trs.length > 1) {
ROOF.Utils.alert('请选择一行记录!','','提示');
ROOF.Utils.hideBlock();
return false;
}
ROOF.Utils.hideBlock();
var id = trs[0].find(":input[name='id']").val();
var urlPath = basePathConst+"/mac/summaryAction/download.action";
DownLoad(urlPath,id);
});
3.使用js的方式创建一个新的form表单,设置1和2得到的下载地址及参数提交到服务器上。
js:
function DownLoad(urlPath,id) {
var form = $("<form>"); //定义一个form表单
form.attr('style', 'display:none'); //在form表单中添加查询参数
form.attr('target', '');
form.attr('method', 'post');
form.attr('action', urlPath);
var input1 = $('<input>');
input1.attr('type', 'hidden');
input1.attr('name', 'id');
input1.attr('value', id);
$('body').append(form); //将表单放置在web中
form.append(input1); //将查询参数控件提交到表单上
form.submit();
}
4.在action方法中处理,使用输入流和输出流输出到页面下载
@RequestMapping("/download")
public void download(Summary summary,HttpServletRequest request, HttpServletResponse response){
Summary sum = summaryService.load(summary);
if (sum != null) {
// 设置读取的字节数
int byteread = 0;
// 取得文件名
String fileName = sum.getFile_name();
InputStream is = null;// 获取url中的输入流
OutputStream os = null;
try {
// 如果是URL方式在得到输入流
URL url = new URL(sum.getFile_path());// 创建URL对象
is = url.openStream();// 获取url中的输入流
os = response.getOutputStream();// 得到响应输出流对象
// 设置下载头信息
fileName = URLEncoder.encode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
response.setContentType("application/octet-stream;charset=UTF-8");
//写入
byte[] buffer = new byte[1204];
while (is != null && (byteread = is.read(buffer)) != -1) {
os.write(buffer, 0, byteread);
}
os.flush();
os.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
if (os != null) {
try {
os.close();
} catch (IOException e) {
}
}
}
}
}