java实现将服务器上的excel文件在web端下载

java实现将服务器上的excel文件在web端下载

问题描述:

 @RequestMapping("/downLoadExcel")
    public void downLoadExcel(String path, HttpServletResponse res){
        path = "D:/workforBoyun/ztc_tool/expert1.xls";
        File file = new File(path);
        try {
            res.setContentType("application/vnd.ms-excel;charset=utf-8");
            String fileName = path.substring(path.lastIndexOf("\\")+1);
            res.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
            InputStream in = new FileInputStream(file);
            int len = 0;
            byte[] buffer = new byte[1024];
            OutputStream out = res.getOutputStream();
            while ((len = in.read(buffer)) > 0) {
                out.write(buffer,0,len);
            }
            in.close();
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

代码这样但不知道为什么 总是输出在web的控制台,求助大神 万分感激

我自己找到原因了 前台用的ajax请求 这样不行 放在href里就好使了 window.open();

很着急 在线等ing

ServletOutputStream out = res.getOutputStream();