将OutputStream发送到浏览器,然后让浏览器保存 [英] Sending OutputStream to browser and let browser save it
问题描述
我想从Rich Faces数据表中导出数据我已经从数据表中的数据创建了outputStream.现在想将此OutputStream发送到浏览器并保存.我该怎么办?
I want to export Data from a Rich Faces Data Table I have created outputStream from the data in the Data Table. Now want to send this OutputStream to browser and let it save. How can I do this?
FileOutputStream stream = new FileOutputStream(new File(PATH));
OutputStream out = myMthodToCreateOutPutStream();
现在如何将该out
保存到浏览器.
Now how to save this out
to browser .
推荐答案
目前尚不清楚您从何处读取数据.您需要创建一个InputStream才能读取数据.
It's not clear where you are reading your data from. You need to create an InputStream to read the data.
然后,您首先需要将响应标头设置为
Then, you first need to set the response headers to
HttpServletResponse.setHeader("Content-Disposition", "attachment; filename=datafile.xls");
使用所需的任何文件名.
Use whatever filename you need.
然后设置mime类型:
Then set the mime-type:
response.setContentType("application/vnd.ms-excel");
使用所需的mime类型.
Use the mime-type you need.
然后需要使用响应对象来获取其输出流-
Then need to use the response object to get its outputstream -
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();
这篇关于将OutputStream发送到浏览器,然后让浏览器保存的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!