正在从 spring java 下载 excel 文件导致文件损坏
Downloading excel file from spring java causing file to corrupt
我正在尝试从我的过滤器调用此方法并且我能够成功下载 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);*/
}
}
问题是响应已经有一个字符串,而代码正在写入附加缓冲区中现有响应的文件。
通过在 setContentType() 之前添加以下代码解决了问题
response.reset();
我正在尝试从我的过滤器调用此方法并且我能够成功下载 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);*/
}
}
问题是响应已经有一个字符串,而代码正在写入附加缓冲区中现有响应的文件。
通过在 setContentType() 之前添加以下代码解决了问题
response.reset();