解决struts不在页面打开下载文件

// 解决struts不在页面打开下载文件 public ActionForward testExecute(ActionMapping mapping, ActionForm form,

    HttpServletRequest request, HttpServletResponse response) throws UnsupportedEncodingException {   

    DynaValidatorForm powerForm = (DynaValidatorForm) form;

   // TODO Auto-generated method stub

         InputStream is=null;

         OutputStream os=null;

         String path = request.getParameter("path");

         /**//*解决中文乱码问题,设置后产生一个新的String对象此对象以改变了编码*/

         String newpath=URLEncoder.encode(path,"utf-8");

         byte[] b=new byte[1024];

         int i=0;

             try {

                 is = new FileInputStream("C:\\Program Files\\Apache Software Foundation\\Tomcat 6.0\\webapps\\Power\\Magazine\\"+path);

                 os = response.getOutputStream();

                 /**//*在页面上弹出一个下在窗口*/

                 response.setContentType("application/x-msdownload");

                 /**//*设置报头信息,弹出窗口中显示的文件名    newpath*/

                 response.setHeader("Content-Disposition", "Disposition; filename="+newpath);

                 /**//*具体的输入输出流操作*/

                 while((i=is.read(b))!=-1){

                     os.write(b, 0, i);

                     i=0;

                 }

                 os.flush();

             } catch (IOException e){

                 // TODO Auto-generated catch block

                 e.printStackTrace();

             }finally{

                 try{

                     os.close();

                     is.close();

                 } catch (IOException e){

                     // TODO Auto-generated catch block

                     e.printStackTrace();

                 }

             }

     return null;

}

posted @ 2013-11-15 13:46  风之宿缘  阅读(155)  评论(0编辑  收藏  举报