在我的 servlet 中,我使用 cookie 传递文件路径并下载文件,如下所示
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String b = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (Cookie cookie : cookies) {
if (cookie.getName().equals("thecookie")) {
b = cookie.getValue();
}
}
}
BufferedReader br = new BufferedReader(new FileReader(b+"/logs.txt"));
String path = br.readLine();
br.close();
File file = new File(path+"/Results.xlsx");
FileInputStream fileIn = new FileInputStream(file);
ServletOutputStream out = response.getOutputStream();
byte[] outputByte = new byte[4096];
//copy binary contect to output stream
while(fileIn.read(outputByte, 0, 4096) != -1)
{
out.write(outputByte, 0, 4096);
}
fileIn.close();
out.flush();
out.close();
}
一切正常,文件正在下载,但是我想下载Results.xlsx
,正在下载的文件是download.zip
,这个download.zip
与我的 Results.xlsx
文件大小相同,但 excel 无法打开。
我该如何正确地做到这一点?
最佳答案
您正在将数据写入输出流,但没有设置内容类型或文件名。您应该使用:
response.setHeader("Content-Disposition", "attachment; filename=Result.xslx");
response.setContentType(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
(在开始写入输出流之前。)
此外,您的流复制循环已损坏 - 即使您没有读那么多,您总是写出 4096 字节。应该是:
int bytesRead;
while((bytesRead = fileIn.read(outputByte)) != -1)
{
out.write(outputByte, 0, byteRead);
}
...并且您应该使用 try-with-resources 或 finally block 来确保关闭流,即使出现异常也是如此。
(或者使用 Guava 等库中的实用方法。)
关于java - 文件下载时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22928812/