网页下载模板前台后台

来源:互联网 发布:htc windows phone 编辑:程序博客网 时间:2024/04/30 16:59

前台

$(function(){    $("tbody").on("click",".dyzs",function(){        window.location.href=ctx+"/tzsb/DCDoc";    });});

当点击时跳转页面,不能用ajax,必须用action或链接。
action

@Action(value="DCDoc", results={@Result(type="json",params={"root","res"})})        public void DCDoc() throws Exception{            res=new ResultObject();            HttpServletResponse response = ServletActionContext.getResponse();            HttpServletRequest request = ServletActionContext.getRequest();            String path = "D:\\wzgzpt\\web\\template";            //String path2 = request.getSession().getServletContext().getRealPath(            //        "/resources");            //String path = "";            String fileName = "气瓶使用登记证.doc";            String filePath = path + "\\" + fileName;            res.setMsg("ok");            publicFunc.downLoadFile(filePath, response, fileName, "doc");        }

downLoadFile方法

public static boolean downLoadFile(String filePath,            HttpServletResponse response, String fileName, String fileType)            throws Exception {            File file = new File(filePath);  //根据文件路径获得File文件            //设置文件类型(这样设置就不止是下Excel文件了,一举多得)            if("pdf".equals(fileType)){               response.setContentType("application/pdf;charset=GBK");            }else if("xls".equals(fileType)){               response.setContentType("application/msexcel;charset=GBK");            }else if("doc".equals(fileType)){               response.setContentType("application/msword;charset=GBK");            }            //文件名            response.setHeader("Content-Disposition", "attachment;filename=\""                + new String(fileName.getBytes(), "ISO8859-1") + "\"");            response.setContentLength((int) file.length());            byte[] buffer = new byte[4096];// 缓冲区            BufferedOutputStream output = null;            BufferedInputStream input = null;            try {              output = new BufferedOutputStream(response.getOutputStream());              input = new BufferedInputStream(new FileInputStream(file));              int n = -1;              //遍历,开始下载              while ((n = input.read(buffer, 0, 4096)) > -1) {                 output.write(buffer, 0, n);              }              output.flush();   //不可少              response.flushBuffer();//不可少            } catch (Exception e) {              //异常自己捕捉                   } finally {               //关闭流,不可少               if (input != null)                    input.close();               if (output != null)                    output.close();            }           return false;        }
0 0
原创粉丝点击