最近在项目里有个下载文件的需求,后台代码写好后,debug时没有出现任何错误信息,但页面就是没有弹出路径供下载选择。然后一直以为是后台代码的问题,结果无意间搜索发现如果想要可以选择下载路径的话,前端需要用window.location.href = 后台方法,才能够实现。
后台代码也贴一下
File file = new File(prePath+backPath);
// 取得文件名。
String fileName = file.getName();
InputStream fis;
try {
fis = new BufferedInputStream(new FileInputStream(filePath));
byte[] buffer = new byte[fis.available()];
fis.read(buffer);
fis.close();
response.reset();
response.addHeader("Content-Disposition",
"attachment;filename=" + new String(fileName.getBytes("gbk"), "ISO-8859-1"));
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 (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
还有前端url传参时后台用request.getParameter(“”)获取