前端下载文件流
downLoad: function (id) {
var url = __ctxPath + '/路径/downLoadFile.action';
$.ajax({
url: url,
type: "POST",
data: {'id': id},
success: function (response, status, request) {
var disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') !== -1) { //判断是否为文件
var form = $('<form method="POST" action="' + url + '">');
$.each({'id': id}, function (k, v) {
form.append($('<input type="hidden" name="' + k +
'" value="' + v + '">'));
});
$('body').append(form);
form.submit(); //自动提交
}
}
});
},
@RequestMapping(value = "/downLoadFile", method = RequestMethod.POST)
public HttpServletResponse exportExcel(Integer id, HttpServletResponse response){
String path = "path";
try {
// path是指欲下载的文件的路径。
File file = new File(path);
// 取得文件名。
String fileName = file.getName();
// 以流的形式下载文件。
InputStream fis = new BufferedInputStream(new FileInputStream(path));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
// 清空response
response.reset();
// 设置response的Header
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName,"UTF-8"));
response.addHeader("Content-Length", "" + file.length());
OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
response.setContentType("application/octet-stream");
toClient.write(buffer);
toClient.flush();
toClient.close();
} catch (IOException ex) {
ex.printStackTrace();
}
return response;
}
更多推荐
ajax下载文件流
发布评论