gpt4 book ai didi

java - 响应头是如何设置的

转载 作者:行者123 更新时间:2023-12-02 04:50:56 24 4
gpt4 key购买 nike

为什么在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com