文件存放位置:web/epms/dbnhpz/moban/托收电费数据模板.xls

调后台方法,将文件存放路径及文件名传到后台。

页面代码:

function down(){
  location.href="download.action?path=epms/dbnhpz/moban&fileFileName=托收电费数据模板.xls";
}

先获取request、response对象,根路径,设置response格式,创建输入、输出流,

response.getOutputStream()将流文件返回到页面。

后台代码:

public String download(){
   ActionContext ctx = ActionContext.getContext();
    HttpServletRequest request = (HttpServletRequest)ctx.get(ServletActionContext.HTTP_REQUEST);
   HttpServletResponse response = ServletActionContext.getResponse();
   String root =request.getSession().getServletContext().getRealPath("/");
   try {
      File file = new File(root+path+"\\"+fileFileName);
       response.setContentType("application/x-msdownload");
      response.setHeader("Content-Disposition","p_w_upload;filename=" 
      + new String(fileFileName.getBytes("gb2312"),"ISO-8859-1"));  
       if(file.exists()){
        java.io.OutputStream os = response.getOutputStream();
        java.io.FileInputStream is = new java.io.FileInputStream(file);
        byte[] b = new byte[1024];
        int i = 0;
        while((i=is.read(b))>0){
          os.write(b,0,i);
        }
        is.close();
        os.flush();
        os.close();
      }
   }catch(Exception e){
     e.printStackTrace();
    }
    return null;
}