2015-03-25 118 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 2015-03-25 11:07:12

回答

2

創建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")); 
相關問題