
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;
}
1343

被折叠的 条评论
为什么被折叠?



