繁体   English   中英

如何设置响应头

[英]How the response header is set

为什么在filenotfound异常之后设置了响应头。 从技术上讲,仅在获取文件后才设置标头。

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();
}

创建File不会引发FileNotFoundException 仅在创建FileInputStream时抛出FileNotFoundException ,此时您已经设置了标头。 尝试像这样重新排列

           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"));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM