Thursday 11 April 2013

jsp code to download file from server

<%
File file = new File("/ed63/ora510/eld611i2comn/html/eisrs/data/backuploadbalance.xlsx");
String resultXLS="excelfileName1441.xlsx";
response.setHeader("Content-Length", ""+file.length());
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet; charset=UTF-8");
response.setHeader("content-disposition", "attachement; filename=\"" + resultXLS + "\"");
response.setHeader("Content-Transfer-Encoding", "binary");

FileInputStream fileIn = new FileInputStream(file);
OutputStream outExcel = response.getOutputStream();

byte[] outputByte = new byte[8192];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 8192) != -1)
{
outExcel.write(outputByte, 0, 8192);
}

fileIn.close();
outExcel.flush();
outExcel.close();

%>

1 comment:

  1. This worked for me, but when I try to open my XLSX file Excel tells me that it "...found unreadable content..." in the file. I select Yes on the prompt to "...recover the contents...", and the content looks ok, but is there a reason why when streaming the content to download it becomes unreadable? When I open the actual file from the server, it opens fine without the prompt, so I assume it has something to do with how I streamed it. Thanks!

    ReplyDelete