40. Upload File in Oracle Server from Local Machine in OAF Page

 

Uploading a File from a Local Machine to the Oracle Server in an OAF Page

Introduction

File upload is a common requirement in Oracle Application Framework (OAF) pages. Whether you need to upload documents, spreadsheets, images, or text files, OAF provides a built-in component called messageFileUpload that allows users to select a file from their local machine and upload it to the server.

This guide walks you through the complete process of creating an OAF page that allows users to upload a file from their local machine to a specified folder on the Oracle server. You will learn how to:

  1. Create the workspace, project, and Application Module

  2. Build the OAF page with a file upload component and an Upload button

  3. Write the controller code to handle the file upload

  4. Read the uploaded file's content and save it to a server directory

  5. Test the file upload functionality


The Four Key Activities

To implement file upload in an OAF page, you need to complete four key activities:

#ActivityPurpose
1Create the Application ModuleContainer that manages access to the model objects
2Create the OAF PageThe user interface with the file upload component
3Create the ControllerHandles the file upload logic
4Write the Upload CodeReads the file stream and writes it to the server

Prerequisites

Before you begin, ensure the following:

  • Oracle JDeveloper is installed and configured with a valid Runtime Connection

  • Database Connection is established

  • You have an EBS user account with the necessary responsibilities

  • You have write access to a directory on the Oracle server (e.g., D:\OAF_WORK in this example)

  • Basic familiarity with creating workspaces, projects, and Application Modules in JDeveloper

Note: The example in this guide uses a Windows server path (D:\OAF_WORK). In a production Linux/Unix environment, use an appropriate path such as /u01/app/OAF_WORK/.


Step 1: Create the Workspace and Project

  1. Create a New OA Workspace:

    • Right-click on Applications

    • Select New OA Workspace

    • Workspace Name: RohitUploadFile

    • Click OK

  2. Configure the Project:

    • Project Name: RohitUploadFile

    • Default Package: rohit.oracle.apps.fnd.RohitUploadFile

Important: The package name determines the directory structure where Java class files and other project files are stored. The oracle.apps.fnd portion is mandatory for OAF development.

  1. Enter Runtime Connection Details:

    • Provide your EBS Username and Password

  2. Complete the Wizard:

    • Click Next, then click Finish


Step 2: Create the Application Module

  1. Open the New Gallery:

    • Right-click on the project RohitUploadFile

    • Select New

  2. Select Application Module:

    • Navigate to Business Tier → ADF Business Components

    • Select Application Module

    • Click OK

  3. Configure the Application Module:

    • Application Module Name: RohitUploadFileAM

    • Default Package: rohit.oracle.apps.fnd.RohitUploadFile.server

  4. Complete the Wizard:

    • Click Next, then click Finish

Important: Every OAF page must be associated with an Application Module. Without this association, the page cannot run.


Step 3: Create the OAF Page

  1. Open the New Gallery:

    • Right-click on the project RohitUploadFile

    • Select New

  2. Select Page:

    • Navigate to Web Tier → JSF/Faces (or Web Tier → Oracle ADF Faces)

    • Select Page

    • Click OK

  3. Configure the Page:

    • Page Name: RohitUploadFilePG

    • Default Package: rohit.oracle.apps.fnd.RohitUploadFile.webui

  4. Rename the Default Region:

    • Select region1

    • Change the ID to PageLayoutRN

  5. Attach the Application Module:

    • With PageLayoutRN selected, set the AM Definition to:

      text
      rohit.oracle.apps.fnd.RohitUploadFile.server.RohitUploadFileAM

Step 4: Create the Main Region

  1. Create a New Region:

    • Right-click on PageLayoutRN

    • Select New → Region

    • A new region (region1) is created

  2. Configure the Region:

    • In the Property Inspector, set:

      • ID: MainRN

      • Region Style: messageComponentLayout

Note: The messageComponentLayout region style is commonly used for form-based layouts, arranging items in a structured, label-field format.


Step 5: Add the File Upload Component

  1. Create the File Upload Item:

    • Right-click on MainRN

    • Select New → messageFileUpload

    • An item (item1) is created

  2. Configure the File Upload Item:

PropertyValue
IDitem1
PromptSelect File

Important: The messageFileUpload component is what renders the Browse button and file selection field on the page. It also handles the file stream when the form is submitted.


Step 6: Add the Upload Button

  1. Create a Layout Region (Optional):

    • Right-click on MainRN

    • Select New → messageLayout

    • A layout region (messageLayout1) is created

  2. Create the Upload Button:

    • Right-click on MainRN

    • Select New → Item

    • An item (item2) is created

  3. Configure the Upload Button:

PropertyValue
IDUpload
Item StylesubmitButton
PromptUpload

Note: The button's ID (Upload) is used in the controller to detect when the button is clicked.


Step 7: Create the Controller

  1. Create the Controller:

    • Right-click on PageLayoutRN

    • Select Set New Controller

  2. Configure the Controller:

    • Controller Name: RohitUploadFileCO

    • Package: rohit.oracle.apps.fnd.RohitUploadFile.webui


Step 8: Write the Controller Code

Open the controller file (RohitUploadFileCO.java) and add the following code.

8.1 Required Import Statements

java
import oracle.apps.fnd.common.VersionInfo;
import oracle.apps.fnd.framework.webui.OAControllerImpl;
import oracle.apps.fnd.framework.webui.OAPageContext;
import oracle.apps.fnd.framework.webui.beans.OAWebBean;
import oracle.cabo.ui.data.DataObject;
import java.io.FileOutputStream;
import java.io.InputStream;
import oracle.jbo.domain.BlobDomain;
import java.io.File;
import oracle.apps.fnd.framework.OAApplicationModule;
import oracle.apps.fnd.framework.OAException;

8.2 Process Form Request

java
public void processFormRequest(OAPageContext pageContext, OAWebBean webBean)
{
    super.processFormRequest(pageContext, webBean);
    
    OAApplicationModule am = pageContext.getApplicationModule(webBean);
    
    if (pageContext.getParameter("Upload") != null)
    {
        upLoadFile(pageContext, webBean);
    }
}

Explanation: When the user clicks the Upload button, the processFormRequest method detects the "Upload" parameter and calls the upLoadFile method.

8.3 The upLoadFile Method

java
public void upLoadFile(OAPageContext pageContext, OAWebBean webBean)
{
    String filePath = "D:\\OAF_WORK";
    System.out.println("Default File Path---->" + filePath);
    
    String fileUrl = null;
    
    try
    {
        // Get the uploaded file data from the messageFileUpload component
        DataObject fileUploadData = pageContext.getNamedDataObject("item1");
        
        if (fileUploadData != null)
        {
            // Get the file name and MIME type
            String uFileName = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_NAME");
            String contentType = (String)fileUploadData.selectValue(null, "UPLOAD_FILE_MIME_TYPE");
            System.out.println("User File Name---->" + uFileName);
            
            FileOutputStream output = null;
            InputStream input = null;
            
            // Get the uploaded byte stream
            BlobDomain uploadedByteStream = (BlobDomain)fileUploadData.selectValue(null, uFileName);
            System.out.println("uploadedByteStream---->" + uploadedByteStream);
            
            // Create the output file on the server
            File file = new File("D:\\OAF_WORK", uFileName);
            System.out.println("File output---->" + file);
            
            output = new FileOutputStream(file);
            System.out.println("output----->" + output);
            
            // Get the input stream from the uploaded blob
            input = uploadedByteStream.getInputStream();
            System.out.println("input---->" + input);
            
            // Read the input stream and write to the output file
            byte abyte0[] = new byte[0x19000];
            int i;
            
            while ((i = input.read(abyte0)) > 0)
                output.write(abyte0, 0, i);
            
            output.close();
            input.close();
        }
    }
    catch (Exception ex)
    {
        throw new OAException(ex.getMessage(), OAException.ERROR);
    }
}

Code Explanation

LinePurpose
String filePath = "D:\\OAF_WORK";Defines the target folder on the server
DataObject fileUploadData = pageContext.getNamedDataObject("item1");Gets the uploaded file data from the messageFileUpload component
String uFileName = ...selectValue(null, "UPLOAD_FILE_NAME");Retrieves the uploaded file name
String contentType = ...selectValue(null, "UPLOAD_FILE_MIME_TYPE");Retrieves the file's MIME type
BlobDomain uploadedByteStream = ...selectValue(null, uFileName);Gets the uploaded file content as a BlobDomain
File file = new File("D:\\OAF_WORK", uFileName);Creates a File object for the target location
output = new FileOutputStream(file);Opens an output stream to write the file
input = uploadedByteStream.getInputStream();Gets the input stream from the uploaded blob
byte abyte0[] = new byte[0x19000];Creates a buffer (100 KB) for reading
while ((i = input.read(abyte0)) > 0)Reads the input stream in chunks
output.write(abyte0, 0, i);Writes each chunk to the output file
output.close(); input.close();Closes the streams
throw new OAException(ex.getMessage(), OAException.ERROR);Wraps any exception in an OAException

Important: The getNamedDataObject("item1") method uses the item ID of the messageFileUpload component. Ensure the ID matches exactly.


Step 9: Rebuild and Run the Project

  1. Rebuild the Project:

    • Right-click on the project RohitUploadFile

    • Select Rebuild

Note: Rebuilding compiles all Java classes and ensures there are no errors before deployment.

  1. Run the Page:

    • After successful compilation, right-click on the project RohitUploadFile

    • Select Run

  2. Test the File Upload:

    • The page opens in your default web browser

    • Click the Browse button to select a file from your local machine

    • Select a file (e.g., BANK_QUERY.txt)

    • Click the Upload button

    • The file is copied to the server directory (D:\OAF_WORK in this example)


How File Upload Works at Runtime

The following illustrates the complete file upload flow:

text
┌─────────────────────────────────────────────────────────────────┐
│                     LOCAL MACHINE                               │
│  1. User clicks the Browse button                               │
│  2. File selection dialog opens                                 │
│  3. User selects a file (e.g., BANK_QUERY.txt)                  │
│  4. User clicks the Upload button                               │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     OAF PAGE                                    │
│  1. Form submitted with the uploaded file                       │
│  2. messageFileUpload component packages the file               │
│  3. File data sent to the server                                │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                     CONTROLLER                                  │
│  1. processFormRequest detects "Upload" parameter               │
│  2. Calls upLoadFile method                                     │
│  3. Retrieves the file data via getNamedDataObject              │
│  4. Reads the file name and content                             │
│  5. Writes the file to the server directory                     │
└─────────────────────────────────────────────────────────────────┘
                              │
                              ▼
┌─────────────────────────────────────────────────────────────────┐
│                    SERVER DIRECTORY                             │
│  1. File saved to D:\OAF_WORK\BANK_QUERY.txt                    │
│  2. File available for further processing                       │
└─────────────────────────────────────────────────────────────────┘

Understanding the messageFileUpload Component

The messageFileUpload component is the key to file upload in OAF. Here's how it works:

AspectDescription
RenderingDisplays a text field and a Browse button
File SelectionOpens the operating system's file selection dialog
Data PackagingPackages the file content as a BlobDomain
Data AccessProvides file name, MIME type, and content via DataObject
Form SubmissionSends the file to the server when the form is submitted

Key DataObject Values

ValueDescription
UPLOAD_FILE_NAMEThe name of the uploaded file
UPLOAD_FILE_MIME_TYPEThe MIME type of the uploaded file
uFileNameThe file content as a BlobDomain

Best Practices

PracticeDescription
Validate File TypesCheck the MIME type to restrict allowed file types
Limit File SizeSet a maximum file size to prevent abuse
Use Secure PathsUse a secure, non-web-accessible directory for uploads
Handle ErrorsWrap file operations in try-catch blocks
Close StreamsAlways close input and output streams
Use Unique NamesConsider adding a timestamp to avoid overwriting files
Log UploadsLog file uploads for auditing purposes
Test in DevelopmentAlways test file uploads in a development environment
Check PermissionsEnsure the server directory is writable by the Oracle user

Troubleshooting Common Issues

IssuePossible CauseSolution
Browse button doesn't appearWrong item typeVerify the item is messageFileUpload
Upload button doesn't workWrong parameter nameVerify the button ID matches the controller check
File not savedWrong directory pathVerify the directory exists and is writable
NullPointerExceptionFile not selectedAdd a null check before processing
"File not found" errorWrong file pathVerify the path uses double backslashes (\\)
Permission deniedDirectory not writableGrant write permissions to the Oracle user
Large files failBuffer size too smallIncrease the buffer size
MIME type errorUnsupported file typeCheck the MIME type and allowed types

Required Import Statements

java
import oracle.apps.fnd.common.VersionInfo;
import oracle.apps.fnd.framework.webui.OAControllerImpl;
import oracle.apps.fnd.framework.webui.OAPageContext;
import oracle.apps.fnd.framework.webui.beans.OAWebBean;
import oracle.cabo.ui.data.DataObject;
import java.io.FileOutputStream;
import java.io.InputStream;
import oracle.jbo.domain.BlobDomain;
import java.io.File;
import oracle.apps.fnd.framework.OAApplicationModule;
import oracle.apps.fnd.framework.OAException;

Summary

Uploading a file from a local machine to the Oracle server in OAF involves the following key steps:

  1. Create the Workspace and Project: Set up the development environment

  2. Create the Application Module: The mandatory container for model objects

  3. Create the OAF Page: The user interface component

  4. Create the Main Region: A messageComponentLayout region to hold the items

  5. Add the File Upload Component: A messageFileUpload item for file selection

  6. Add the Upload Button: A submitButton to trigger the upload

  7. Create the Controller: Handle the upload event

  8. Write the Upload Code: Read the file stream and write it to the server

  9. Rebuild and Test: Compile and verify the file upload functionality

Key Points to Remember

  • The messageFileUpload component provides the Browse button and file selection

  • The getNamedDataObject("item1") method retrieves the uploaded file data

  • The UPLOAD_FILE_NAME and UPLOAD_FILE_MIME_TYPE values provide file metadata

  • The BlobDomain object holds the file content

  • The FileOutputStream writes the file to the server directory

  • Always close streams and handle exceptions properly

  • Use double backslashes (\\) in Windows paths within Java strings

Why This Matters

File upload is essential for many Oracle E-Business Suite business processes, including:

  • Document Management: Uploading contracts, invoices, and supporting documents

  • Data Import: Uploading CSV or Excel files for batch processing

  • Image Upload: Uploading product images or employee photos

  • Report Generation: Uploading templates for report generation

  • Integration: Uploading files for interfacing with external systems

By mastering file upload in OAF, you can build pages that allow users to submit files directly through the Oracle E-Business Suite interface, eliminating the need for manual file transfers or FTP.


References

  • Oracle E-Business Suite Documentation: OA Framework Developer's Guide

  • Oracle JDeveloper Documentation: Available in the jdevdoc folder

  • Related Guides: Creating an LOV in OAF, Creating a Search Page in OAF, Controller Extension in OAF, Using PL/SQL Packages in OAF

No comments:

Post a Comment