【问题标题】:Sending OutputStream to browser and let browser save it [duplicate]将OutputStream发送到浏览器并让浏览器保存它[重复]
【发布时间】:2012-07-31 02:37:00
【问题描述】:

我想从 Rich Faces 数据表中导出数据,我从数据表中的数据创建了 outputStream。现在想将此 OutputStream 发送到浏览器并保存。我该怎么做?

FileOutputStream stream = new FileOutputStream(new File(PATH));

OutputStream out = myMthodToCreateOutPutStream();

现在如何将这个out 保存到浏览器。

【问题讨论】:

    标签: jsf richfaces export-to-excel


    【解决方案1】:

    不清楚您从哪里读取数据。您需要创建一个 InputStream 来读取数据。

    然后,您首先需要将响应标头设置为

    HttpServletResponse.setHeader("Content-Disposition", "attachment; filename=datafile.xls");
    

    使用您需要的任何文件名。

    然后设置mime-type:

    response.setContentType("application/vnd.ms-excel");
    

    使用您需要的 mime 类型。

    然后需要使用响应对象来获取它的输出流——

    OutputStream outStream = response.getOutputStream();
    

    现在写给它:

    byte[] buf = new byte[4096];
    int len = -1;
    
    //Write the file contents to the servlet response
    //Using a buffer of 4kb (configurable). This can be
    //optimized based on web server and app server
    //properties
    while ((len = inStream.read(buf)) != -1) {
        outStream.write(buf, 0, len);
    }
    
    outStream.flush();
    outStream.close();
    

    【讨论】:

    • 这个答案给了我一个提示来解决我的问题。非常感谢
    猜你喜欢
    • 2010-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-18
    • 2019-01-17
    • 1970-01-01
    • 2014-08-10
    • 1970-01-01
    相关资源
    最近更新 更多