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

冷暖自知 提交于 2019-11-30 10:37:40

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();
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!