为什么在 filenotfound 异常之后设置响应头。 从技术上讲, header 仅在获取文件后设置。
try {
//codes
File file = new File(zipDestinationPath);
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
response.setContentLength((int)file.length());
response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
is = new FileInputStream(file);
FileCopyUtils.copy(is, response.getOutputStream());
} catch(FileNotFoundException e){
System.out.println("File Not Found.");
ServletOutputStream out = null;
try {
//i am not setting header here commentedit.
// response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode("Error", "UTF-8"));
response.setContentType("text/plain;charset=ISO-8859-15");
out = response.getOutputStream();
System.out.println(("Invalid file path :" +zipDestinationPath).getBytes());
out.write(("Invalid file path :" +zipDestinationPath).getBytes());
out.flush();
out.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
catch (Exception e) {
e.printStackTrace();
}
最佳答案
创建文件
不会抛出FileNotFoundException
。仅当您创建 FileInputStream
时才会引发 FileNotFoundException
,此时您已经设置了 header 。尝试重新排列它,就像
File file = new File(zipDestinationPath);
is = new FileInputStream(file);
response.setContentType(new MimetypesFileTypeMap().getContentType(file));
response.setContentLength((int)file.length());
response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
关于java - 响应头是如何设置的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29253842/