Java I/O實現OAF文件上傳與下載 – JAVA編程語言程序開發技術文章

文件上傳
   首先建立用於存放附件的臨時視圖對象(View Object),包含Blob類型的視圖屬性(View Attribute),建立頁面包含messageFileUpload類型的Item,並創建頁面的控制器。
   在控制器的processFormRequest中編寫以下代碼:
   try
   {
   OAViewObject vo = (OAViewObject)am.findViewObject("FileVO1");
   Row row = vo.getCurrentRow();
  
   String filePath = "/u01/demo10/demo10comn/temp/";
  
   BlobDomain blob = (BlobDomain)row.getAttribute("FileData");
   File f = new File(filePath + (String)row.getAttribute("FileName"));
   InputStream is = blob.getBinaryStream();
   FileOutputStream fos = new FileOutputStream(f);
  
   int size=blob.getBufferSize();
   byte[] buffer=new byte[size];
   int len;
  
   while((len=is.read(buffer)) != -1)
   {
   fos.write(buffer,0,len);
   }
   is.close();
   fos.flush();
   fos.close();
   }
   catch(IOException ex)
   {
   ex.printStackTrace();
   System.out.println(ex.getMessage());
   }
  
   文件下載
   這裡要實現的功能是當單擊附件鏈接時,能自動打開附件保存對話框,代碼如下:
   try
   {
   OAViewObject vo = (OAViewObject)am.findViewObject("FileVO1");
   Row row = vo.getCurrentRow();
  
   BlobDomain blob = (BlobDomain)row.getAttribute("FileData");
   HttpServletResponse response = (HttpServletResponse)pageContext.getRenderingContext().getServletResponse();
   response.addHeader("Content-Disposition", "attachment;filename="+ (String)row.getAttribute("FileName"));
   response.setContentType("application/x-msdownload");
  
   InputStream is = blob.getBinaryStream();
   int size=blob.getBufferSize();
   byte[] buffer=new byte[size];
   int len;
  
   while((len=is.read(buffer)) != -1)
   {
   response.getOutputStream().write(buffer,0,len);
   }
   is.close();
   response.getOutputStream().flush();
   response.getOutputStream().close();
   }
   catch(IOException ex)
   {
   ex.printStackTrace();
   System.out.println(ex.getMessage());
   }

 

作者“紅豆加奶”

發佈留言