Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sending OutputStream to browser and let browser save it [duplicate]

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 .

like image 787
waseemwk Avatar asked Dec 15 '22 21:12

waseemwk


1 Answers

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();
like image 78
Rajesh J Advani Avatar answered Apr 26 '23 20:04

Rajesh J Advani