使用servletOutputStream下载的XLS文件显示无效的文件内容.请给我建议把它修好



我正在使用以下代码从我的Web应用程序下载并显示xls文件。使用无效字符下载文件(如䡗ⰱㅂ〬ⰱ).请告诉我在这个代码中缺少什么。

String contentDisposition = "attachment";
String fileName = "Test.xls";
String path = "/xxx/yyy";
final int BUFFER = 1024; 
byte servletBytes[] = new byte[BUFFER];
ServletOutputStream out = response.getOutputStream();
FileInputStream fis = new FileInputStream(new File(path));
ByteArrayOutputStream bout = new ByteArrayOutputStream();
int count = 0;
while ((count = fis.read(servletBytes)) > 0) {
bout.write(servletBytes, 0, count);
}
fis.close();
servletBytes = bout.toByteArray();
bout.close();
out.write(servletBytes);
response.setContentType("Application/vnd.ms-excel;charset=UTF-8");
if (contentDisposition.length() > 0) {
response.setHeader("Content-Disposition", contentDisposition + ";filename=" + fileName);
}
out.flush();
out.close();
if (fis != null) {
fis.close();
}
if (bout != null) {
bout.close();
}

设置内容Disposition和文件名应该在写入Stream之前,我还优化了代码这样我们就可以避免使用Servlet名称下载文件的问题

String contentDisposition = "attachment";
String path = "/test/ship.xls";
byte servletBytes[] = new byte[BUFFER];
ServletOutputStream out = response.getOutputStream();
FileInputStream fis = new FileInputStream(new File(path));
response.setContentType("Application/vnd.ms-excel;charset=UTF-8");
if (contentDisposition.length() > 0) {
response.setHeader("Content-Disposition", contentDisposition + ";filename=" + 
new File(path).getName());
}
int count = 0;
while ((count = fis.read(servletBytes)) > 0) {
out.write(servletBytes, 0, count);
}
fis.close();
out.flush();
out.close();

下面的代码适用于我。下载了文件内容,但使用了servlet文件名。请帮助解决。

String contentDisposition = "attachment";
String path = "/test/ship.xls";
byte servletBytes[] = new byte[BUFFER];
ServletOutputStream out = response.getOutputStream();
FileInputStream fis = new FileInputStream(new File(path));
int count = 0;
while ((count = fis.read(servletBytes)) > 0) {
out.write(servletBytes, 0, count);
}
fis.close();
response.setContentType("Application/vnd.ms-excel;charset=UTF-8");
if (contentDisposition.length() > 0) {
response.setHeader("Content-Disposition", contentDisposition + ";filename=" + new File(path).getName());
}
out.flush();
out.close();

最新更新