Chinaunix首页 | 论坛 | 博客
  • 博客访问: 202733
  • 博文数量: 42
  • 博客积分: 2520
  • 博客等级: 少校
  • 技术积分: 392
  • 用 户 组: 普通用户
  • 注册时间: 2008-12-26 16:41
文章分类

全部博文(42)

文章存档

2010年(4)

2009年(38)

我的朋友

分类: Java

2010-06-21 11:05:59

public ActionForward exportFile(ActionMapping mapping, ActionForm form, HttpServletRequest request,
            HttpServletResponse response) throws Exception {
        String natLog = "test";
                
        try {
            StringBuilder fileName = null;
            OutputStream output = null;
            
            byte[] streamBytes = natLog.getBytes();
            if (streamBytes == null) {

            } else {
                fileName = new StringBuilder(64);
                fileName.append("export.txt");
                try {
                    output = response.getOutputStream();
                    
                    FileStream.initResponseAsFile(response, fileName.toString(), "MIME/octet-strea");
                    output.write(streamBytes);
                    output.flush();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    if (output != null) {
                        output.close();
                    }
                }
            }
        }
        catch(Exception e) {
            e.printStackTrace();
            return null;
        }
        
        return null;
    }

 

public static void initResponseAsFile(HttpServletResponse resp,    String fileName, String fileType)
            throws UnsupportedEncodingException {
        
        String[] names = fileName.split("\\.");
        String filename = "attachment; filename="
                + new String(names[0].getBytes("GBK"), "ISO8859_1") + "."
                + names[1];
        resp.setCharacterEncoding("charset=GBK");
        resp.setHeader("Content-Disposition", filename); //设定输出文件头


        //定义输出类型

        if (fileType.equals("excel")) {
            resp.setContentType("application/vnd.ms-excel");
        }
        else if(fileType.equals("xml")) {
            resp.setContentType("application/vnd.ms-xml");
        }
        else if(fileType.equals("txt")) {
            resp.setContentType("text/plain");
        }
        else if(fileType.equals("csv")){
            resp.setContentType("application/CSV");
        }
        else if(fileType.equals("MIME/octet-strea")) {
            resp.setContentType("text/plain");
        }
        else {
            resp.setContentType("application/vnd.ms-excel");
        }
            
        
    }


阅读(771) | 评论(0) | 转发(0) |
0

上一篇:jsp 用urlrewrite 实现URL 重写

下一篇:没有了

给主人留下些什么吧!~~