Spring mvc 作为Spring响应传输excel文件时数据丢失
我的用例是让我的应用程序从服务器下载excel(.xls)。excel中应该有图表 这是它的服务器端代码Spring mvc 作为Spring响应传输excel文件时数据丢失,spring-mvc,file-transfer,Spring Mvc,File Transfer,我的用例是让我的应用程序从服务器下载excel(.xls)。excel中应该有图表 这是它的服务器端代码 @RequestMapping(value="/downloadExcel", method=RequestMethod.GET) public void download(HttpServletRequest request, HttpServletResponse response) { String fileName = "excel.xls"; response.s
@RequestMapping(value="/downloadExcel", method=RequestMethod.GET)
public void download(HttpServletRequest request, HttpServletResponse response) {
String fileName = "excel.xls";
response.setContentType("APPLICATION/vnd.ms-excel");
response.addHeader("Content-Disposition", "attachment; filename=" + fileName);
try {
Files.copy(new File(fileName), (OutputStream)response.getOutputStream());
response.getOutputStream().flush();
} catch (Exception e) {
e.printStackTrace();
}
}
打开excel时,我收到一条警告消息,提示“文件错误:数据可能已丢失”。而且,我在下载的excel中看不到图表
我还检查了将内容类型设置为“OCTET-STREAM”,但没有成功
response.setContentType("APPLICATION/OCTET-STREAM");
如何传输excel文件而不丢失数据?我使用此代码,可以下载带有图形的excel文件
void copyFileToResponse(HttpServletResponse response, File file) throws IOException {
if(file != null) {
String mimeType = URLConnection.guessContentTypeFromName(file.getName());
if (mimeType == null) {
logger.debug("mimetype is not detectable, will take default");
mimeType = "application/octet-stream";
}
logger.debug("mimetype : {}", mimeType);
response.setContentType(mimeType);
response.setHeader("Content-Disposition", String.format("attachment; filename=\"%s\"", file.getName()));
response.setContentLength((int) file.length());
InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
FileCopyUtils.copy(inputStream, response.getOutputStream());
}
}
你能不能把文件上传到某个地方,这样我就可以试着下载相同的文件,并检查是否有相同的错误?