这个问题在这里已经有了答案:
How to provide a file download from a JSF backing bean?
(5 个回答)
6年前关闭。
我想从 Rich Faces 数据表中导出数据,我从数据表中的数据创建了 outputStream。现在想将此 OutputStream 发送到浏览器并保存。我怎样才能做到这一点?FileOutputStream stream = new FileOutputStream(new File(PATH));
OutputStream out = myMthodToCreateOutPutStream();
现在如何保存 out
到浏览器。
最佳答案
目前尚不清楚您从哪里读取数据。您需要创建一个 InputStream 来读取数据。
然后,您首先需要将响应 header 设置为
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();
关于jsf - 将 OutputStream 发送到浏览器并让浏览器保存它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11772120/