web后台文件下载,打开新窗口

先看下前端

<div class="tab-pane fade" id="box_tab5">
  <div class="alert alert-info">
	<h3><strong>节点mac</strong></h3>
	<span><input style="width:120px" type="text" class="form-control" id="mac" name="mac"></span>
  </div>
  <div class="doc-dd">
    <input style="width:120px;height:30px" id="start" name="act_start_time" type="text" class="text-box" value="" placeholder="开始时间" title="开始时间" readonly="readonly" style="cursor:pointer;"/>
    <input style="width:120px;height:30px" id="end" name="act_stop_time" type="text" class="text-box" value="" placeholder="结束时间" title="结束时间" readonly="readonly" style="cursor:pointer;"/>     <input style="width:120px;height:30px" class="btn btn-xs btn-info" type="button" value="生成报表" onClick="javascript:search()">     <input style="width:120px;height:30px" class="btn btn-xs btn-info" type="button" value="下载报表" onClick="window.open('${ctx}/download')">   </div> </div>

  

再看下后台

public void fileDownload(Model model, HttpServletResponse response,
		HttpServletRequest request) throws Exception {
  String filePath =  "C:\\nms\\tongji.xls";
   BufferedInputStream bis = null;
   BufferedOutputStream bos = null;
 
    bis = new BufferedInputStream(new FileInputStream(filePath));
    bos = new BufferedOutputStream(response.getOutputStream());
 
    long fileLength = new File(filePath).length();
 
    response.setCharacterEncoding("UTF-8");
    response.setContentType("multipart/form-data");
    /*
     * 解决各浏览器的中文乱码问题
     */
    String fileName = "tongji.xls";
    String userAgent = request.getHeader("User-Agent");
    byte[] bytes = userAgent.contains("MSIE") ? fileName.getBytes()
            : fileName.getBytes("UTF-8"); // fileName.getBytes("UTF-8")处理safari的乱码问题
    fileName = new String(bytes, "ISO-8859-1"); // 各浏览器基本都支持ISO编码
    response.setHeader("Content-disposition",
            String.format("attachment; filename=\"%s\"", fileName));
 
    response.setHeader("Content-Length", String.valueOf(fileLength));
    byte[] buff = new byte[2048];
    int bytesRead;
    while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
        bos.write(buff, 0, bytesRead);
    }
    bis.close();
    bos.close();
}

  

posted @ 2015-12-04 14:40  桃源仙居  阅读(540)  评论(0)    收藏  举报