【发布时间】:2021-02-15 07:45:49
【问题描述】:
我正在尝试从我的过滤器中调用此方法,并且我能够成功下载 excel,但是下载后当我打开 excel 时它显示它已损坏,但是当我看到服务器文件上的文件打开时没有任何错误。
Excel 错误:excel 无法打开文件“文件名”,因为文件格式或文件扩展名无效。
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);*/
}
}
【问题讨论】: