Struts 2 完成直接输出流到浏览器

Struts 2 完成直接输出流到浏览器
2008年10月17日 星期五 上午 10:30

// 告诉Struts 执行完 Action 就行了,不用再去调用结果响应的操作
ActionContext.getContext().getActionInvocation().getProxy().setExecuteResult(false);

// 取得 HttpServletResponse
HttpServletResponse response = ServletActionContext.getResponse();

// 下面是输出(一定要注意编码)
        InputStream in = null;
        try {
            response.setContentType("xls");
            response.setHeader("Content-Disposition", "attachment; filename=" + encode(fileName + ".xls"));
           
            OutputStream os = response.getOutputStream();
           
            in = new FileInputStream(file);
            int tp = in.read();
            while (tp != -1) {
                response.getOutputStream().write(tp);
                tp = in.read();
            }
            os.flush();
        } catch (Throwable e) {
            logger.info("文件下载失败!", e);
            throw new RuntimeException("文件下载失败!", e);
        } finally {
            try {
                in.close();
            } catch (IOException e) {
                logger.info("关闭流失败!", e);
                throw new RuntimeException("关闭流失败!", e);
            }
        }

你可能感兴趣的:(浏览器,struts,OS)