I have a web interface which is used to download a file. When the request comes in, my glassfish server streams the file from a web service and then writes the content to the outputstream. My code works fine except when the file size becomes very large (like more than 200 MB), it hangs showing 0% donwloaded in the browser and the file is never downloaded.
When I move flush() method inside the while loop it works fine for large files as well. I am not sure if putting flush() in a loop is a problem. Not sure how this thing actually works. My code is as follows :
HttpURLConnection conn = (HttpURLConnection) downloadUri.toURL().openConnection();
conn.setDoOutput(true);
conn.setRequestMethod("GET");
conn.setRequestProperty("Content-Type", "application/pdf");
if (conn.getResponseCode() == 200) {
ServletOutputStream output;
try (InputStream inputStream = conn.getInputStream()) {
HttpServletResponse response = (HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse();
response.setContentType("application/octet-stream");
response.setHeader("Content-Length", conn.getHeaderField("Content-Length"));
response.setHeader("Content-Disposition", "attachment; filename=\"" + abbr + ".pdf\"");
output = response.getOutputStream();
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
}
output.flush();
output.close();
Any thoughts?. Thank you for looking into this.
output.flush()
forces the stream to output whatever it has buffered. If you don't flush the downloaded bytes will be stored inoutput
until it flushes itself. Not sure when that happens. – Renatorenaudflush()
is outside the loop and closes the connection? The loop doesn't realize the connection is closes, but continues to try to read from the inputStream eternally. – Renatorenaud