如何设置响应标头

时间:2015-03-25 11:02:38

标签: java java-ee

为什么在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();
}

1 个答案:

答案 0 :(得分:2)

创建File不会抛出FileNotFoundException。只有在您创建FileNotFoundException时才会引发FileInputStream,此时您已经设置了标头。尝试重新排列,如

           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"));
相关问题