2015-03-25 116 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")); 
相关问题