将OutputStream发送到浏览器并让浏览器保存它

Was*_*han 4 jsf richfaces export-to-excel

我想从Rich Faces数据表中导出数据我已经从数据表中的数据创建了outputStream.现在想要将此OutputStream发送到浏览器并让它保存.我怎样才能做到这一点?

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

OutputStream out = myMthodToCreateOutPutStream();

现在如何将此保存out到浏览器.

Raj*_*ani 12

目前尚不清楚您从何处阅读数据.您需要创建一个InputStream来读取数据.

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

HttpServletResponse.setHeader("Content-Disposition", "attachment; filename=datafile.xls");
Run Code Online (Sandbox Code Playgroud)

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

然后设置mime类型:

response.setContentType("application/vnd.ms-excel");
Run Code Online (Sandbox Code Playgroud)

使用你需要的mime类型.

然后需要使用响应对象来获取其输出流 -

OutputStream outStream = response.getOutputStream();
Run Code Online (Sandbox Code Playgroud)

现在写信给它:

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();
Run Code Online (Sandbox Code Playgroud)