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



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

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

OutputStream out = myMthodToCreateOutPutStream();

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

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

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

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

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

然后设置mime类型:

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();

最新更新