Sending OutputStream to browser and let browser sa

2019-02-07 09:46发布

问题:

This question already has an answer here:

  • How to provide a file download from a JSF backing bean? 4 answers

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 .

回答1:

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