struts报Cannot forward after response has been committed問題

来源:互联网 发布:模拟植物生长算法 编辑:程序博客网 时间:2024/06/06 13:14
public void downLoadFile(ActionEvent event) throws DatabaseException {
        
try {
            FacesContext faces 
= FacesContext.getCurrentInstance();
            ExternalContext extContext 
= faces.getExternalContext();
            String filePath 
= extContext.getApplicationMap().get("filePath")
                    .toString();
            UIParameter component 
= (UIParameter) event.getComponent()
            .findComponent(
"deleteId");
            
int id = Integer.parseInt(component.getValue().toString());
            Seg_Files b 
= DAOFactory.getSeg_FilesDAO().getSeg_FilesById(id);
            String fileName 
= filePath+ b.getFileName();
            
//System.out.println(fileName);
            ByteArrayOutputStream baos=FileUtils.downloadFile(fileName);
            
            
//獲得文件的ByteArrayOutputStream結束
            
            HttpServletResponse response 
= (HttpServletResponse) faces.getExternalContext().getResponse();    
            
//response.setHeader("Content-disposition", "attachment; filename="+ b.getFileName());
            
//response.setContentType("text/txt; charset=utf-8");
            response.setHeader("Content-disposition""attachment; filename="+ b.getFileName());
            response.setContentType(
"application/txt;charset=utf-8");
            response.setContentLength(baos.size());
            ServletOutputStream sos 
= response.getOutputStream();
            baos.writeTo(sos);
            baos.close();
            sos.flush();
            
//需要呼叫Complete,要不就報:Cannot forward after response has been committed
            faces.responseComplete();
            
        }
 catch (IOException ex) {
            System.out.println(ex);
        }

    }
 
public static ByteArrayOutputStream downloadFile(String fileName) throws IOException {
        
        FileInputStream fis
=new FileInputStream(fileName);
        BufferedInputStream bis
=new BufferedInputStream(fis);
        ByteArrayOutputStream baos
=new ByteArrayOutputStream();
        BufferedOutputStream bos
=new BufferedOutputStream(baos);
        
        
int i;
        
while((i=bis.read())!=-1{
          bos.write(i);
        }

        bos.flush();
//must have
        bis.close();
        
        
return baos;
    }
原创粉丝点击