效果如图:
1、web端
downFile:function(projectAttachId){
var a = document.createElement('a');
a.href = baseUrl + 'km/attachFileEs/downFile?projectAttachId='+ projectAttachId;
document.body.appendChild(a);
a.click();//触发下载
document.body.removeChild(a);
},
2.java 端
/**
* 文件下载
* @author Mike
* @param request
* @param response
* @param projectAttachId
*/
@RequestMapping(value = "/downFile", method = RequestMethod.GET)
public void downFile(HttpServletRequest request, HttpServletResponse response,String projectAttachId) {
String filePath = "F:\\ZFU资料\\年中十讲笔记完整版.pdf";
String fileName="年中十讲笔记完整版.pdf";
// System.out.println(fileName);
File file = new File(filePath);
InputStream is = null;
OutputStream os = null;
// 设置头部
try {
is = new FileInputStream(file);
response.setContentType("application/octet-stream");
String ContentD = "attachment;filename=" + URLEncoder.encode(fileName , "UTF-8").replace("+","%20");
response.setHeader("Content-Disposition", ContentD.replaceAll("(?:\t|\n|:)", ""));
// 写入到本地response
os = response.getOutputStream();
byte[] buffer = new byte[1024];
int i = is.read(buffer);
while (i != -1) {
os.write(buffer, 0, i);
i = is.read(buffer);
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finally {
try {
is.close();
} catch (IOException e) {
logger.error("InputStream关闭异常", e);
}
try {
if (null != os) {
os.close();
}
} catch (IOException e) {
logger.error("OutputStream关闭异常", e);
}
}
}