rolling stone
rolling stone

Reputation: 645

How the response header is set

Why does the response header is set after a filenotfound exception. Technically the headers are set only after getting the file.

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

Upvotes: 0

Views: 811

Answers (1)

Evan Knowles
Evan Knowles

Reputation: 7511

Creating a File does not throw a FileNotFoundException. The FileNotFoundException is only thrown when you create the FileInputStream, at which point you've already set the headers. Try rearranging it like

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

Upvotes: 2

Related Questions