2015-03-25 2 views
0

Почему заголовок ответа устанавливается после исключения 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

Похоже, что этот файл удален и доступен через HTTP, можете ли вы подтвердить это? – Opentuned

ответ

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")); 
Смежные вопросы