ADF Faces File Uploading – It is really that simple!

26

One particularly type of interaction in web applications is typically a little bit tricky. Requiring additional analysis of the frameworks used. For me personally it was even the way to get started with Java technology (Jason Hunter’s Servlet Programming – that’s where for me it all began). I am talking about File Uploading. Functionality required in many applications, and frequently causing some headaches. I am working on an ADF project where we are considering offering an "Excel upload’ facility as method for getting data into the application. Doing some initial investigations, it struck me how extremely simple and straightforward the implementation of file upload with ADF Faces really is!

 

The steps:....

  • set the usesUpload property of the af:form element to true
  • add an af:inputFile element to the form
  • bind the value attribute of this inputFile to a managed bean property of type UploadedFile (oracle.adf.view.faces.model.UploadedFile)
  • write code in the setter method for this property to actually do something with the uploaded file contents

And this is all you need to do! Let’s create a simple example that will serve as our stepping stone for uploading CSV and Excel files. We will create a simple application that can upload text files and display their contents and several file details:

Let’s first create a new JDeveloper Application with a new Project. In this project, create a new JSF page (FileUpload.jspx).

Use the af:form tag instead of the h:form and set the usesUpload attribute to true:

<af:form usesUpload="true"> 

Add an inputFile element: 

&lt;af:inputFile label=&quot;File to Upload&quot; columns=&quot;90&quot; <br />                          value=&quot;#{FileProcessor.uploadedFile}&quot;/&gt;<br />            &nbsp;<br />

and tie its value attribute to a managed bean – that we will create in just a moment. 

Add a PanelForm with a number of fields to display the properties of the uploaded file:

&lt;af:panelForm&gt;<br />  &lt;af:inputText label=&quot;File Name&quot; value=&quot;#{FileProcessor.filename}&quot; readOnly=&quot;true&quot;/&gt;<br />  &lt;af:inputText label=&quot;File Size&quot; value=&quot;#{FileProcessor.filesize}&quot; readOnly=&quot;true&quot;/&gt;<br />  &lt;af:inputText label=&quot;File Type&quot; value=&quot;#{FileProcessor.filetype}&quot; readOnly=&quot;true&quot;/&gt;<br />  &lt;af:inputText label=&quot;File Contents&quot; value=&quot;#{FileProcessor.filecontents}&quot; columns=&quot;220&quot; rows=&quot;30&quot; /&gt;<br />&lt;/af:panelForm&gt;<br />

Create the Java Class that will handle the uploaded file:

package nl.amis.adffaces.files;<br /><br />import java.io.IOException;<br /><br />import oracle.adf.view.faces.model.UploadedFile;<br /><br />public class FileProcessor {<br />    private UploadedFile uploadedFile;<br />    private String filename;<br />    private long filesize;<br />    private String filecontents;<br />    private String filetype;<br /><br />    public FileProcessor() {<br />    }<br /><br />    public void setUploadedFile(UploadedFile uploadedFile) {<br />        this.uploadedFile = uploadedFile;<br />        this.filename = uploadedFile.getFilename();<br />        this.filesize = uploadedFile.getLength();<br />        this.filetype = uploadedFile.getContentType();<br />        try {<br />            this.filecontents = parseISToString(uploadedFile.getInputStream());<br />        } catch (IOException e) {<br />            // TODO<br />        }<br />    }<br /><br />    public UploadedFile getUploadedFile() {<br />        return uploadedFile;<br />    }<br /><br />    public void setFilename(String filename) {<br />        this.filename = filename;<br />    }<br /><br />    public String getFilename() {<br />        return filename;<br />    }<br /><br />    public void setFilesize(long filesize) {<br />        this.filesize = filesize;<br />    }<br /><br />    public long getFilesize() {<br />        return filesize;<br />    }<br /><br />    public void setFilecontents(String filecontents) {<br />        this.filecontents = filecontents;<br />    }<br /><br />    public String getFilecontents() {<br />        return filecontents;<br />    }<br /><br />    public void setFiletype(String filetype) {<br />        this.filetype = filetype;<br />    }<br /><br />    public String getFiletype() {<br />        return filetype;<br />    }<br /><br />    // from: http://www.bubble-media.com/cgi-bin/articles/archives/000038.html<br /><br />    public String parseISToString(java.io.InputStream is) {<br />        java.io.DataInputStream din = new java.io.DataInputStream(is);<br />        StringBuffer sb = new StringBuffer();<br />        try {<br />            String line = null;<br />            while ((line = din.readLine()) != null) {<br />                sb.append(line + &quot;\n&quot;);<br />            }<br />        } catch (Exception ex) {<br />            ex.getMessage();<br />        } finally {<br />            try {<br />                is.close();<br />            } catch (Exception ex) {<br />            }<br />        }<br />        return sb.toString();<br />    }<br />}<br />&nbsp;

And finally configure the FileProcessor managed bean in the faces-config.xml file.

&lt;managed-bean&gt;<br />    &lt;managed-bean-name&gt;FileProcessor&lt;/managed-bean-name&gt;<br />    &lt;managed-bean-class&gt;nl.amis.adffaces.files.FileProcessor&lt;/managed-bean-class&gt;<br />    &lt;managed-bean-scope&gt;request&lt;/managed-bean-scope&gt;<br />&lt;/managed-bean&gt;<br /><br />

Now we can run the JSF page. We can press the browse button, select a file, press the Start Upload button and have the file uploaded to the application server. The FileProcessor Bean’s setUploadedFile method is invoked and the properties and contents are extracted from the UploadedFile object and set on the other bean properties.

Resources

Download JDeveloper 10.1.3.2 Application: ADFFacesUploadFile.zip.

Share.

About Author

Lucas Jellema, active in IT (and with Oracle) since 1994. Oracle ACE Director for Fusion Middleware. Consultant, trainer and instructor on diverse areas including Oracle Database (SQL & PLSQL), Service Oriented Architecture, BPM, ADF, Java in various shapes and forms and many other things. Author of the Oracle Press book: Oracle SOA Suite 11g Handbook. Frequent presenter on conferences such as JavaOne, Oracle OpenWorld, ODTUG Kaleidoscope, Devoxx and OBUG. Presenter for Oracle University Celebrity specials.

26 Comments

  1. Dear Lucas
    Thank you for your interesting article.  Actually it was very helpful!
    Now I need a “progress bar” for my “file uploading”, showing the percent of completion, especially for the files with  huge size.
    I don’t know how to do this part of the code. I’ll be thankful if you guide me on this matter.
    Regards.
     

  2. hi,
     
    i managed to run the sample on the Jdev 11.1.2 :)
    here is what i did.
    . first i downloaded jfreereport-0.8.6.jar (for ExcelProcessor class) and jcommon-1.0.15.jar (for StackableException class) via jar search.
    . then replaced the <managed-bean-class>nl.amis.adffaces.excel.ExcelProcessor</managed-bean-class> with <managed-bean-class>org.jfree.report.modules.output.table.xls.ExcelProcessor</managed-bean-class>
    then ran the sample :-)
    hope this helps
    vosime

  3. Hi
    Using your program where(location)will the file be placed on to server .
    In my case if I am running from local then the file should be uploaded to my local jdev directory structure. But I dont find the file uploaded.

    Thanks

  4. i tried excel instead of text file. It is unable to read excel data , displaying in unreadable format .
    i tried to put  

     FileInputStream fis = fis = new FileInputStream(this.uploadedfile.getInputStream);
                    HSSFWorkbook workbook = new HSSFWorkbook(fs);
                    HSSFSheet sheet = workbook.getSheetAt(0);

    i’m getting error , “FileinputStream(uploadfile) can not invoke FileInputStream(File)”.

    i aslo tried to put  his.filecontents = parseISToString(uploadedFile.getInputStream()). giving me error file format/content can not resolve.

    any sample code or link that could help me to solve the issue
    thanks

  5. Hi ,
           It is working fine with .txt ,but i need using excel sheet. can any one me with this

  6. Awesome, thx, Im using Oracle JDev 11g and I dont use this oracle.adf.view.faces.model.UploadedFile Instead im Using org.apache.myfaces.trinidad.model.UploadedFile

    I fallow one by one of ur Steps and every goes just great. the only thing, I create a Button with label “Start Uploading!” with no code and default properties, just to upload the file selected.

    And Now I will try upload a picture. Any help with this?

  7. I’m working on jdev 11.1.1.0.1. There seems no more class (oracle.adf.view.faces.model.UploadedFile). Instead, there is only org.apache.myfaces.trinidad.model.UploadedFile. Even in Oracle document http://download.oracle.com/docs/cd/E12839_01/web.1111/b31973/af_input.htm#BABDFAEI, it teaches people to use trinidad.

    I follow Oracle’s documentation but receive this error java.lang.ClassCastException: mypackage.view.myBackingBean cannot be cast to javax.servlet.Filter

    So, do I need to declare mybacking bean as a filter?

  8. hey man, i need to upload files with a filesize greater than 50MB, but i have problems, with the file size, i had modified the init properties inthe web.xml, but it does not work, any idea?

  9. Suhana Redzwan on

    Hi there..this is a cool stuff…but I wanted to save the file to a physical location..how can i do this?

  10. Very useful!.
    I tested that in jDeveloper 10.1.3.3, and it works. Just a warning appeared in class “FileProcessor.java”, that was “DataInputStream readLine is deprecated”, but you can solve this using java class “BufferedReader” instead “DataInputStream”, like this:

    Before: java.io.DataInputStream din = new java.io.DataInputStream(is);
    After: BufferedReader din = new BufferedReader(new InputStreamReader(is));

  11. Ash Manukyan on

    Hi, I am a newbie in Jdeveloper and I was wondering if anybadoy has a .pdf or something with steps to configure enad register an adf in EBS 11.5.10.x or R12.
    Regards

  12. I need to upload the file from client to server. By using this application how will I know where the file is saved in server? I need it as a file, not only the contents. Thanks.

  13. could anybody tell me all the jar that i need for that application to make it rannable in ecplise-tomcat envirnment and the settings.

  14. hello….this application is running on jdeveloper11g..but it is not running on eclipse-tomcat envirnment..may be i have missed nay jar file.could u pls tell me to make this runnable there what all i have to do?

  15. Robert,

    I am not sure exactly what you are doing, but it seems you are mixing up client and server with this approach. The ADF Middle Tier knows nothing about paths on the (browser) client. It cannot reach those paths, it is not allowed to. If in your case the webclient happens to be a machine the ADF Middle Tier happens to be able to get to, that is a coincidence that the architecture does not cater for – you still cannot get path information from the browser. Nor can you preset the value of the upload file item: that must be set by the user!

    Sorry, but I am afraid I cannot help you.

    Lucas

  16. I need the path for open an xml file, read it and with the data i just read execute a query for save this data in the database.

    String url = “file:\\C:\\jdevstudio10133\\file.xml”;
    SAXBuilder builder=new SAXBuilder(false);
    Document doc= builder.build(url);

    As you can see i specified the path but i need to let the user choose the xml file, so when he does that i need to obtain the path to execute the process

  17. You do not get the path – after the file has been uploaded, it just has a name. For security reasons, the path on the browser-machine is not available to the server. (what would you need it for anyway?)

    Lucas

  18. Thank you for your reply. However when i tried to make the same in Jdeveloper11g, the property of type oracle.adf.view.faces.model.UploadedFile gives an error(“not found”) . Also in the function MyProgressRangeModel, the method createValueBinding and GetValue have been deprecated in JDeveloper11g. Can you provide an alternate solution to that please?

    Thank you.

  19. Now I download ADFFacesUploadFile.zip. And I try it.
    At first time, three lines in jspx file have problem:
    xmlns:h=”http://java.sun.com/jsf/html”
    xmlns:f=”http://java.sun.com/jsf/core”
    xmlns:afh=”http://xmlns.oracle.com/adf/faces/html”
    xmlns:af=”http://xmlns.oracle.com/adf/faces”
    After installing jsp lib, it works.

    But in faces-config.xml, has managed bean ExcelProcessor.
    And I could not find it’s java code.

    ExcelProcessor
    nl.amis.adffaces.excel.ExcelProcessor
    request

  20. I follow the instruction to crate an application in Jdeveloper. It works. However, when I trying to load other file, the file name, file type, and file size fields show the right information. The file contents files display the old file contents.
    I will appreciate if you can offer the code to refresh the file contents field and show the current file contents.

    (try send again)

  21. Yes I did. It really is this simple! The inputFile element is linked to the FileProcessor.uploadedFile property. This property is of type oracle.adf.view.faces.model.UploadedFile. When the Upload button is pressed the form is submitted and the uploadedFile property is set by ADF Faces. To check out the details, please download the zipfile you find under Resources.

  22. U provided the code for browsing the file, but no code sample have been provided for the “start upload” button.

  23. First: DataInputStream readLine is deprecated.

    Second: It would be great if you included a HOW TO for uploading BLOB/CLOB into the database using ADF.

    Third: Appreciate your work.

    Kind Regards,

    Dave