This question already has an answer here:
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();
Now how to save this out
to browser .
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.
Then set the mime-type:
response.setContentType("application/vnd.ms-excel");
Use the mime-type you need.
Then need to use the response object to get its outputstream -
OutputStream outStream = response.getOutputStream();
Now write to it:
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();
来源:https://stackoverflow.com/questions/11772120/sending-outputstream-to-browser-and-let-browser-save-it