jsp前台:jsp代码内潜入隐藏的form
<div class="accordion">
<map name="FPMap0">
<area href="#" οnclick="downloads();" shape="rect" coords="7, 198, 181, 250">
</map>
<ul style="display: inline-block;">
<img src="${ctx}/images/lc.gif" usemap="#FPMap0"/>
</ul>
</div>
<span style="color:#ff0000;"><form id="uploadForm" action="${ctx}/upload/downloadFile" method="post">
<input type="hidden" name="fileName" id="fileName" />
</form></span>
提交form的js 方法:
<span style="white-space:pre"> </span><pre name="code" class="javascript">function downloads() {
var fileName="密码重置受理表.doc";
$("#fileName").val(fileName);
$("#uploadForm").submit();
}
controllor 层方法实现
@RequestMapping("/downloadFile")
public String download(String fileName, HttpServletResponse response) {
try {
String path = getRequest().getSession().getServletContext().getRealPath("/") + "docs/" + fileName;
logger.info("#downloadFile#path=" + path);
File file = new File(path);
response.reset();
response.setContentType("application/octet-stream;charset=UTF-8");
response.addHeader("Content-Length", "" + file.length());
String agent = getRequest().getHeader("USER-AGENT");
/*if (null != agent && -1 != agent.indexOf("MSIE") || null != agent && -1 != agent.indexOf("Trident")) {// ie
fileName = java.net.URLEncoder.encode(fileName, "UTF8");
} else if (null != agent && -1 != agent.indexOf("Mozilla")) {// 火狐,chrome等
fileName = new String(fileName.getBytes("UTF-8"), "iso-8859-1");
}*/
fileName = new String(fileName.getBytes("gbk"), "iso-8859-1");
response.setHeader("Content-disposition", "attachment; filename=" + fileName);
InputStream inputStream = new FileInputStream(file);
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 返回值要注意,要不然就出现下面这句错误!
// java+getOutputStream() has already been called for this response
return null;
}