我有一个 servlet 正在生成 .xls
文件,然后将生成的文件发送给用户以供下载,代码如下:
// Write the output to a file
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter=
new SimpleDateFormat("yyyy_MMM_dd");
String dateNow = formatter.format(currentDate.getTime());
String path = "webapps/myapp/exports/";
String fileName = ("Table_export_"+ dateNow + ".xls");
FileOutputStream fileOut = new FileOutputStream(path+fileName);
wb.write(fileOut);
fileOut.close();
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
文件保存在服务器上,大小为 5 kb,但在浏览器对话框中选择“保存”或“打开”后,文件为空,大小为 0 kb。我不明白出了什么问题。
我与这个问题斗争了大约两个小时,但没有成功。我尝试设置完整路径:
response.setHeader("Content-Disposition","attachment;filename="path+fileName);
但是我得到了一个名称很奇怪的文档,而且它的大小也是 0 kb。
我很确定我错过了一些非常小的东西,但作为一名初级开发人员,我仍然无法弄清楚。
最佳答案
由于您已经有了一种可以将文件写入输出流的方法,因此您可以简单地以这种方式更改代码以将其发送给用户:
Calendar currentDate = Calendar.getInstance();
SimpleDateFormat formatter = new SimpleDateFormat("yyyy_MMM_dd");
String dateNow = formatter.format(currentDate.getTime());
String fileName = ("Table_export_"+ dateNow + ".xls");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition","attachment;filename="+fileName);
OutputStream outputStream = response.getOutputStream();
try {
wb.write(outputStream);
} finally {
outputStream.close();
}
但它不会保存在您的服务器硬盘上。
方法 HttpServletResponse#getOutputStream()
允许您访问将发送回客户端的字节流。
关于java - 奇怪的 Servlet 响应问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17443510/