前端代码
第一步:在jsp对应的地方加上下面的代码
<iframe style="display: none;" id="download_iframe"></iframe>
第二步:定义点击事件下载文件
<a id="attachFile" onclick="downLoad('http://downloadFile?fileId=fastuser/M00/00/03/CsL9JFwXPAyATC9OAAkVVGMybN8085.jpg','Hydrangeas.jpg')" href="javascript:void(0)"><i class="icon icon-attach" style="margin-top:4px"></i></a>
function downLoad(url,fileName){
//对中文文件进行编码,防止ie因为编码问题,而导致的服务没有反应
var fileName2 = encodeURI(fileName);
url = url +"&fileName="+fileName2;
$("#download_iframe").attr("src", url);
}
@RequestMapping("/downloadFile")
public void downloadFile(String fileId,String fileName, HttpServletRequest request,HttpServletResponse response) throws FileNotFoundException {
byte[] content = null;
try {
content = FDFSUtil.download(fileId);
response.setContentType("Image/" + fileName); // 设置相应类型,告诉浏览器输出的内容为图片
response.setHeader("Pragma", "No-cache"); // 设置响应头信息,告诉浏览器不要缓存此内容
response.setHeader("Cache-Control", "no-cache");
response.setHeader("Content-Disposition", "attachment;filename=" + ExcelUtil.toUtf8String(fileName));
OutputStream toClient = response.getOutputStream();
toClient.write(content);
toClient.flush();
toClient.close();
} catch (Exception e) {
e.printStackTrace();
}
}