Please disable your adblock and script blockers to view this page

Search this blog

Monday, 4 August 2014

Uploading and downloading files from absolute server path in Oracle ADF (12.1.3)

Hello all
this post is about a very simple requirement -file handling (uploading and downloading various types of file) in ADF and it is needed very often to store file in absolute server path (actual path) and download from there

see step by step implementation -
  • I have created a simple table in HR schema to store uploaded file name ,path and content type
  • See sql script for this table-

     CREATE TABLE "FILE_UPD_DWN" 
       ( "FILE_NAME" VARCHAR2(50 BYTE), 
     "PATH" VARCHAR2(100 BYTE), 
     "CONTENT_TYPE" VARCHAR2(500 BYTE)
       )
    

  • Then prepare model using this table and drop on page as af:table, and an af:inputFile to select and upload file is used in page


  • Then create a ValueChangeListener on inputFile component to upload file to an actual path on server, and after upload a row is inserted in table to keep record of uploaded files

  • Bean Method to Upload File-


        /**Method to upload file to actual path on Server*/
        private String uploadFile(UploadedFile file) {
    
            UploadedFile myfile = file;
            String path = null;
            if (myfile == null) {
    
            } else {
                // All uploaded files will be stored in below path
                path = "D://FileStore//" + myfile.getFilename();
                InputStream inputStream = null;
                try {
                    FileOutputStream out = new FileOutputStream(path);
                    inputStream = myfile.getInputStream();
                    byte[] buffer = new byte[8192];
                    int bytesRead = 0;
                    while ((bytesRead = inputStream.read(buffer, 0, 8192)) != -1) {
                        out.write(buffer, 0, bytesRead);
                    }
                    out.flush();
                    out.close();
                } catch (Exception ex) {
                    // handle exception
                    ex.printStackTrace();
                } finally {
                    try {
                        inputStream.close();
                    } catch (IOException e) {
                    }
                }
    
            }
            //Returns the path where file is stored
            return path;
        }
    

    AMImpl method to insert record in table for Uploaded file




        /**Method to set file path and name
         * @param name
         * @param path
         */
        public void setFileData(String name, String path,String contTyp) {
            ViewObject fileVo = this.getFileUpdDwn1();
            Row newRow = fileVo.createRow();
            newRow.setAttribute("FileName", name);
            newRow.setAttribute("Path", path);
            newRow.setAttribute("ContentType", contTyp);
            fileVo.insertRow(newRow);
            this.getDBTransaction().commit();
            fileVo.executeQuery();
        }
    

    ValueChangeListener to execute all methods -




        /*****Generic Method to Get BindingContainer**/
        public BindingContainer getBindingsCont() {
            return BindingContext.getCurrent().getCurrentBindingsEntry();
        }
    
        /**
         * Generic Method to execute operation
         * */
        public OperationBinding executeOperation(String operation) {
            OperationBinding createParam = getBindingsCont().getOperationBinding(operation);
            return createParam;
    
        }
    
        /**Method to Upload File ,called on ValueChangeEvent of inputFile
         * @param vce
         */
        public void uploadFileVCE(ValueChangeEvent vce) {
            if (vce.getNewValue() != null) {
                //Get File Object from VC Event
                UploadedFile fileVal = (UploadedFile) vce.getNewValue();
                //Upload File to path- Return actual server path
                String path = uploadFile(fileVal);
                System.out.println(fileVal.getContentType());
                //Method to insert data in table to keep track of uploaded files
                OperationBinding ob = executeOperation("setFileData");
                ob.getParamsMap().put("name", fileVal.getFilename());
                ob.getParamsMap().put("path", path);
                ob.getParamsMap().put("contTyp", fileVal.getContentType());
                ob.execute();
                // Reset inputFile component after upload
                ResetUtils.reset(vce.getComponent());
            }
        }
    

  • Now run application and select files and see- 


  • See uploaded files in folder


  • I have seen that developers often use servlet to download and open file in browser window using HTTP response , but no need to to do this as ADF provides built in component for this <af:fileDownloadActionListener> that automatically generate http response
  • Now Upload part is complete , for download functionality added a link in table column and dropped an af:fileDownloadActionListener inside link and set properties for DownloadActionListener



  • See the code in Download Listener

  •     /**Method to download file from actual path
         * @param facesContext
         * @param outputStream
         */
        public void downloadFileListener(FacesContext facesContext, OutputStream outputStream) throws IOException {
            //Read file from particular path, path bind is binding of table field that contains path
            File filed = new File(pathBind.getValue().toString());
            FileInputStream fis;
            byte[] b;
            try {
                fis = new FileInputStream(filed);
    
                int n;
                while ((n = fis.available()) > 0) {
                    b = new byte[n];
                    int result = fis.read(b);
                    outputStream.write(b, 0, b.length);
                    if (result == -1)
                        break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
            outputStream.flush();
        }
    

  • Now run application and see how Upload and download works 

Happy Learning :) Sample ADF Application

Next Post is this series - (Must Read)
Uploading mulitiple files to server path in Oracle ADF using af:inputFile
Uploading and downloading files from database (BLOB) in Oracle ADF

31 comments :

  1. I am not able to download file.It shows an error.

    ReplyDelete
    Replies
    1. Hi Shruti

      Have you checked sample application ?
      Please explain in detail when n where you are facing error and what is that error ?

      Ashish

      Delete
  2. Great post, appreaciated greatly. I will share a scenario and hope if you can share some light. If a user uploads a file, but changes his mind and rollbacks everything, the files will still remain on the server, can you give me some ideas on how to work around this. I don't think permissions are an issue in my case.

    ReplyDelete
    Replies
    1. When user rollbacks at that time you can delete file from server path , For this you need file name and server path where it is stored

      File directory = new File(path);
      //get all the files from a directory
      File[] fList = directory.listFiles();

      for (File file : fList) {
      fileNm = file.getName();
      //Write logic here to match file name and delete it
      }

      Ashish

      Delete
  3. Hi Ashish,

    My app is working perfectly on integrated server, run Windows. But when I deploy app to server linux, and change path "/home/oracle/folder/", it shows error NullpointerException. Can u fix that? thanks

    ReplyDelete
    Replies
    1. Hoangmai

      This doesn't look like ADF issue, I think you should double check path for linux
      Where you are getting NullPointer ?

      Ashish

      Delete
    2. Ashish,
      Thank for your help.
      I fixed it, because of the folder permission

      Delete
  4. Really very helpful post,,,

    Can we do same in lower versions like 11g?

    ReplyDelete
  5. Hai Ashish,
    My requirment is that, when user click on Print ( a PDF file will open in new window,(frm I reports, I done this)) then it will be automatically send to his mail ID.
    so How to automatically store and mail to his mail ID.

    I done upto when user click on print button invoice will open in window.
    After that I dnt have an idea how to do, Thanks in advance

    ReplyDelete
    Replies
    1. Sree

      Are you storing this PDF somewhere ?
      If yes then you can send file from that path using java mail
      Check this - Send eMail and attachement from any SMTP server using JavaMail in Oracle ADF

      If No then first save this file on some fixed path and then attach it to mail

      Ashish

      Delete
  6. hi ,
    if there is an error in file download listener , i want to show error message in the UI , how can i show message in the page , JsfUtil.addError message is not showing in the page .

    Thanks
    Raj

    ReplyDelete
  7. hi ashish my requirement is that when user clicks on a button it should open a word document with static text...can u tel me this how to do?i have done till opening a blank word document after that I duno

    ReplyDelete
    Replies
    1. So what's the problem with word file with Text ?
      Do you want to write a file at runtime ?

      Delete
    2. yes developing hr template...have done a coding on the button ut its not writng nor showing in the word document

      Delete
    3. You can use this simple java code to wirte a word file and then open it

      try {
      FileWriter fw = new FileWriter("D://Test.doc");
      fw.write("This is sample static text");
      fw.close();
      } catch (IOException e) {
      }

      Delete
    4. public class Opentempdoc {
      @SuppressWarnings("oracle.jdeveloper.java.unconventional-field-modifier-order")
      //static protected OutputStream outputStream;

      private static OutputStream OutputStream;

      public Opentempdoc() {
      // String str_template="temp1";
      // String strContent = readTemplate(str_template);
      // writeTemplate(strContent,str_template);
      }

      @SuppressWarnings("oracle.jdeveloper.java.insufficient-catch-block")

      public String readTemplate(String hrTemp) {
      //this method used to read template content and return to that content
      String content = null;
      String filepath="C:\\Users\\ganeshai\\Documents\\KPIdashboard\\aiswarya.txt";
      System.out.println("file path: " + filepath);
      BufferedReader br = null;

      try {

      // String sCurrentLine=null;

      br = new BufferedReader(new FileReader(filepath));

      while ((br.readLine()) != null) {
      content = content + br.readLine();
      System.out.println("current line: " + content);
      }

      } catch (IOException e) {
      e.printStackTrace();
      System.out.println("exception while reading");
      }
      System.out.println("final content" + content);
      return content;
      }

      Delete
  8. public void writeTemplate(String content, String hrTemplate) {
    //this method used to wite template content in new file
    File file = new File("C:\\Users\\ganeshai\\Documents\\KPIdashboard\\aiswary_copy.txt");
    System.out.println("file: " + file);
    try{

    // if file doesnt exists, then create it
    if (!file.exists()) {
    file.createNewFile();
    System.out.println("new file creation block");
    }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(content);
    bw.close();

    System.out.println("Done");

    } catch (IOException e) {
    e.printStackTrace();
    System.out.println("file wirte exception");
    }
    }


    public void b1_action(FacesContext FacesContext, OutputStream outputStream) {
    // String filepath="C:\\Users\\ganeshai\\Documents\\KPIdashboard\\temp1.docx";
    // String content = "this is sample data to test";//getDownloadData();
    String str_template="aiswarya";
    String strContent = readTemplate(str_template);
    // String strContent = "this is sample content";
    System.out.println("doc content:" + strContent);


    //System.out.println("Heloooooo: "+Data);
    // save to the output stream
    try {
    //System.out.println(Data);
    File file = new File("C:\\Users\\ganeshai\\Documents\\KPIdashboard\\aiswary_copy.txt");
    System.out.println("file: " + file);

    // if file doesnt exists, then create it
    if (!file.exists()) {
    file.createNewFile();
    System.out.println("new file creation block");
    }

    FileWriter fw = new FileWriter(file.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(strContent);
    bw.close();

    System.out.println("Done");

    } catch (IOException e) {
    e.printStackTrace();
    System.out.println("file wirte exception");
    }

    ReplyDelete
  9. public void c3_attributeChangeListener(AttributeChangeEvent attributeChangeEvent) {
    // Add event code here...
    }
    public String b1_action() {
    // Add event code here...
    return "Hello";
    }
    I have written this code..is there anything wrong?

    ReplyDelete
    Replies
    1. I can't read all the code Aiswarya
      You should check that yourself , I have suggested you the way to write data in a doc file and you can use download listener or servlet to open file
      Still if you don't get your problme solved then post this question on OTN Forum

      Ashish

      Delete
  10. Hi Ashish,
    I have requirment, we have two buttons,when click on button file will open in pdf and excel,
    I'm using Jasper reports,
    I done upto Pdf generation by using your tutor, Its so much helpful,and now when I click on another button I want to open report in EXCEL formate,
    what I need to change on that code, please help me through that ASAP.
    Thanks in advance

    ReplyDelete
    Replies
    1. You can not opne excel in browser directly for that you need to use some kind of plugin, Yes you can create report in excel format using jasper report

      Ashish

      Delete
  11. Hi I'm Ali from Iraq
    I like your sample adf application
    I have question.
    When I'm add adf security to this application I get error

    OracleJSP error: oracle.jsp.parse.JavaCodeException: Line # 14, oracle.jsp.parse.JspParseTagScriptlet@17370e83
    Error: Java code in jsp source files is not allowed in ojsp.next mode.

    ReplyDelete
  12. Hi Ashish,

    If I have to download a file from remote machine then how can I achieve that in adf?

    Thanks

    ReplyDelete
    Replies
    1. Check this - http://stackoverflow.com/questions/11724576/read-remote-file-in-java-which-needs-username-and-password

      Delete
  13. where can i put ValueChangeListener code to execute all methods ??

    ReplyDelete
  14. Error(156,40): cannot find symbol; symbol: method getOperationBinding(java.lang.String); location: interface oracle.adf.model.BindingContainer
    in:
    /**
    * Generic Method to execute operation
    * */
    public OperationBinding executeOperation(String operation) {
    OperationBinding createParam = getBindingsCont().getOperationBinding(operation);
    return createParam;

    }
    what is a problem?

    ReplyDelete
  15. Dear Ashish,
    i try to run this in jsff page , but i get error ????
    when i run it in jsf its run good, why this do not run in jsff?

    ReplyDelete