Issue
I am trying to call this method from my filter and i am successfully able to download the excel but after the download when i open the excel it shows that it is corrupted but when i see the file on server files opens fine without any error.
Excel error : excel cannot open the file "filename" because the file format or file extension is not valid.
public static void downloadFileFromServer(HttpServletResponse response, String sourceFile,
Boolean isFilenameHavingTimestamp,Boolean deleteTempFile) throws IOException, Exception {
logger.debug("Inside ServiceUtils.downloadFileFromServer()");
// splitting serverPath and fileName
String serverHomeDirectory[] = sourceFile.split("\\\\|/");
String fileName = serverHomeDirectory[serverHomeDirectory.length - 1];
fileName = URLDecoder.decode(fileName, "UTF-8");
if (Boolean.TRUE.equals(isFilenameHavingTimestamp)) {
fileName = removeTimestampFromFilename(fileName);
}
response.setContentType("application/octet-stream");
response.addHeader("content-disposition", "attachment; filename=\"" + fileName + "\"");
try (ServletOutputStream out = response.getOutputStream();
FileInputStream in = new FileInputStream(sourceFile);) {
int octet = 0;
while ((octet = in.read()) != -1) {
out.write(octet);
}
} catch (Exception e) {
logger.error("Exception in ServiceUtils.downloadFileFromServer(): ", e);
throw new Exception(ExceptionMessage.ERROR_DOWNLOAD_EXCEL_FILE);
} finally {
// check if file needs to be deleted after download
/*if(deleteTempFile)
deleteTempFile(sourceFile);*/
}
}
Solution
Problem was that the response already had a string and code was writing the file appending the existing response in the buffer.
Solved the problem by adding below code before setContentType()
response.reset();
Answered By - user8588354