Tuesday, May 28, 2013

To Download file from Server in OAF

/**
* @param pageContext the current OA page context
* @param file_name_with_path - this is fully qualified file name with its path on unix application
* server. eg "/xxcrp/xxapplcrp/mukul/abc.pdf"
* @param file_name_with_ext - this is file name with extension, you wanna display user
* for download. eg- i wanna display the abc.pdf file download with name five_point_someone.pdf
* then I can pass this as "five_point_someone.pdf"
*/
public void downloadFileFromServer(OAPageContext pageContext,
                                  String file_name_with_path,
                                  String file_name_with_ext) {
  HttpServletResponse response = (HttpServletResponse) pageContext.getRenderingContext().getServletResponse();
  if (((file_name_with_path == null) || ("".equals(file_name_with_path)))){
    throw new OAException("File path is invalid.");
  }

  File fileToDownload = null;
  try{
    fileToDownload = new File(file_name_with_path);
  }catch (Exception e){
    throw new OAException("Invalid File Path or file does not exist.");
  }

  if (!fileToDownload.exists()){
    throw new OAException("File does not exist.");
  }

  if (!fileToDownload.canRead()){
    throw new OAException("Not Able to read the file.");
  }

  String fileType = "application/pdf";//getMimeType(file_name_with_ext);
  response.setContentType(fileType);
  response.setContentLength((int)fileToDownload.length());
  response.setHeader("Content-Disposition", "attachment; filename=\"" + file_name_with_ext + "\"");

  InputStream in = null;
  ServletOutputStream outs = null;

  try{
    outs = response.getOutputStream();
    in = new BufferedInputStream(new FileInputStream(fileToDownload));
    int ch;
    while ((ch = in.read()) != -1){
      outs.write(ch);
    }
  }catch (IOException e){
    // TODO
    e.printStackTrace();
  }finally{
    try{
      outs.flush();
      outs.close();
      if (in != null){
        in.close();
      }
    }catch (Exception e){
      e.printStackTrace();
    }
  }
}
Source:http://mukx.blogspot.in/search/label/OAF
Related Posts Plugin for WordPress, Blogger...