Title: Downloading file stops just before finish - caused by Content Length in response header
Tags: java;jakarta-ee;download
Question: The following code is used to prepare a file to be downloaded:

```File downloadFile = new File(ftpPath + File.separator + company.toLowerCase() + File.separator + "download" + File.separator + paramFileName);
FileInputStream fis = new FileInputStream(downloadFile);
BufferedInputStream bis = new BufferedInputStream(fis);


response.setContentType("binary");
response.setHeader("Content-Disposition", "attachment; filename="+paramFileName);

response.setHeader("Content-Length",String.valueOf(downloadFile.length()));
response.setHeader("Content-Encoding", "utf-8");

ServletOutputStream sos = response.getOutputStream();

IOUtils.copy(bis, sos);

sos.flush();
fis.close();
bis.close();
sos.close();
```

When a file is clicked and downloaded, while the total file size is correctly visible in the download progress bar, the file never actually finishes downloading. For large files, it gets about 95%+ of the way there and then stops completely. For smaller files, the results are less consistent, but the file never finishes downloading in it's entirety.

If I remove the following lines, the file does completely download:

```/*
response.setHeader("Content-Length",String.valueOf(downloadFile.length()));
response.setHeader("Content-Encoding", "utf-8");
*/
```

However, the total file size is not given when the file begins downloading. This is very inconvenient for our users, who may be downloading a large file and would like to know an approximate "time to completion" number.

Is there a fix which will allow the file to completely download and also give an accurate indication of the file size?

Thanks for the help

Note: Got rid of DataInputStream as it was never used.




{'source': 'StackExchangeDataset', 'subset': 'stackoverflow.com', 'metadata': {'AnswerCount': 0, 'CommentCount': 0, 'ContentLicense': 'CC BY-SA 3.0', 'CreationDate': '2014:00:04/21/14', 'FavoriteCount': None, 'PostTypeId': 1, 'Tags': '<java><jakarta-ee><download>', 'Title': 'Downloading file stops just before finish - caused by Content Length in response header', 'ViewCount': 397, 'id': 23197884, 'user_AboutMe': '', 'user_AccountId': 2353211.0, 'user_DisplayName': 'Mr. Loop', 'user_Reputation': 167.0, 'user_Views': 26.0, 'user_id': 2061609.0}}