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

Sharing is Caring

Hello all
this post is about a very simple requirement -file handling (uploading and downloading files of the different type) in ADF and it is needed very often to store the 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 the page as af:table, and an af:inputFile to select and upload file is used in the page

 

 

    • Then create a ValueChangeListener on the inputFile component to upload the file to an actual path on the server, and after upload, a row is inserted in the table to keep a 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 a record in the 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 the application and select files and see-

 

 

    • See uploaded files in the folder

 

 

    • I have seen that developers often use the servlet to download and open a file in the browser window using HTTP response, but no need to to do this as ADF provides a 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 the link and set properties for DownloadActionListener

 

Uploading and downloading files

 

 

    • 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 the application and see how Upload and download works

Happy Learning 🙂 Sample ADF Application

Next Post in this series – (Must Read)
Uploading multiple files to server path in Oracle ADF using af:inputFile
Uploading – downloading files from the database (BLOB) in Oracle ADF

Related Posts

An Oracle ACE, Blogger, Reviewer, Technical Lead working on Oracle ADF

33 thoughts on “Uploading and downloading files from absolute server path in Oracle ADF (12.1.3)”

  1. 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.

  2. 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

  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

  4. 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

  5. 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

  6. 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

  7. 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) {
    }

  8. 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;
    }

  9. 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");
    }

  10. 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?

  11. 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

  12. 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

  13. 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.

  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?

  15. Dear Ashish,
    Thanx for this blog really helpful

    My application is running well when i run it on local system. when i deploy on production server it giving this error
    ADF_FACES-60097:For more information, please see the server’s error log for an entry beginning with: ADF_FACES-60096:Server Exception during PPR, #4
    my path on server is “/u02/FileStore_Usman”
    Please help

Leave a Reply

Your email address will not be published. Required fields are marked *