JQuery的ajax函數(shù)的返回類型只
有xml铸屉、text钉蒲、json、html等類型彻坛,沒有“流”類型,所以我們要實(shí)現(xiàn)ajax下載踏枣,不能夠使用相應(yīng)的ajax函數(shù)進(jìn)行文件下載昌屉。但可以用js
生成一個(gè)form,用這個(gè)form提交參數(shù)茵瀑,并返回“流”類型的數(shù)據(jù)间驮。在實(shí)現(xiàn)過程中,頁面也沒有進(jìn)行刷新马昨。
function fileModelDownload() {var form = $("
"); //定義一個(gè)form表單form.attr('style', 'display:none'); //在form表單中添加查詢參數(shù)form.attr('target', '');form.attr('method', 'post');form.attr('action', "fupUser/fileModelDownload.do");var input1 = $('');input1.attr('type', 'hidden');input1.attr('name', 'strUrl');$('body').append(form); //將表單放置在web中form.append(input1); //將查詢參數(shù)控件提交到表單上form.submit();}
后臺(tái)
// 文件模板下載
@RequestMapping("/fupUser/fileModelDownload")
@ResponseBody
public void fileModelDownload(HttpServletRequest request, HttpServletResponse response) throws IOException{
File file = new File(request.getSession().getServletContext().getRealPath("/") + "/download/fupUser.txt");
if(file.exists()){
OutputStream os = response.getOutputStream();
try {
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=fupUser.txt");
response.setContentType("application/octet-stream; charset=utf-8");
os.write(FileUtils.readFileToByteArray(file));
os.flush();
} finally {
if (os != null) {
os.close();
}
}
}
}