Sun. Oct 24th, 2021

Requirement: I want to Upload a File in the Absolute Server Path, and the details about the uploaded files will be stored in the Oracle Database Table.

Then in the user interface, we will be having the table displaying the file details and one of the columns in this table is the Download hyperlink on click of which it will download the corresponding file.

Solution: For the solution of the above requirement follow the steps as shown below.

Step 1: Create a file_upload_download table in the Oracle Database. The table creation script is as below:

CREATE TABLE file_upload_download (
    file_name     VARCHAR2(50),
    file_path     VARCHAR2(100),
    content_type  VARCHAR2(500)
);

Step 2: Create an ADF Fusion Web Application. Create a ADF Business Components from Tables for the file_upload_download table.

Step 3: Create an AppModuleImpl.java class and write the below setFileData method.

public void setFileData(String name, String path, String contTyp) {
    ViewObject fileVo = this.getFileUploadDownloadVO1();
    Row newRow = fileVo.createRow();
    newRow.setAttribute("FileName", name);
    newRow.setAttribute("FilePath", path);
    newRow.setAttribute("ContentType", contTyp);
    fileVo.insertRow(newRow);
    this.getDBTransaction().commit();
    fileVo.executeQuery();
}

Expose setFileData method as a Client Interface.

Step 4: Create a fileUploadDownloadDemo.jspx file in the VewController project.

Drag and drop af:panelCollection and set featuresOff=”viewMenu detach”

Drag and drop af:toolbar inside the toolbar facet of the af:panelCollection

Drag and drop af:inputFile inside the af:toolbar and set label=”Browse and Upload”, autoSubmit=”true”, and
valueChangeListener=”#{pageFlowScope.FileUploadDownloadBean.browseAndUploadFileVCE}”

Drag and drop FileUploadDownloadVO1 from the the AppModuleDataControl as an ADF Table. Please remove the ContentType column.

Add and af:column inside which add af:link and set text=”Download”

Inside the af:link drag and drop af:fileDownloadActionListener and set filename=”#{row.bindings.FileName.inputValue}” and method=”#{pageFlowScope.FileUploadDownloadBean.downloadFileListener}”

Just a note, please make sure that the af:form has usesUpload=”true”

Thus, the complete code for the fileUploadDownloadDemo.jspx is shown below:

<?xml version='1.0' encoding='UTF-8'?>
<jsp:root xmlns:jsp="http://java.sun.com/JSP/Page" version="2.1" xmlns:f="http://java.sun.com/jsf/core"
          xmlns:af="http://xmlns.oracle.com/adf/faces/rich">
    <jsp:directive.page contentType="text/html;charset=UTF-8"/>
    <f:view>
        <af:document title="fileUploadDownloadDemo.jspx" id="d1">
            <af:messages id="m1"/>
            <af:form id="f1" usesUpload="true">
                <af:panelCollection id="pc1" featuresOff="viewMenu detach">
                    <f:facet name="menus"/>
                    <f:facet name="toolbar">
                        <af:toolbar id="t1">
                            <af:inputFile label="Browse and Upload" id="if1" autoSubmit="true"
                                          valueChangeListener="#{pageFlowScope.FileUploadDownloadBean.browseAndUploadFileVCE}"/>
                        </af:toolbar>
                    </f:facet>
                    <f:facet name="statusbar"/>
                    <af:table value="#{bindings.FileUploadDownloadVO1.collectionModel}" var="row"
                              rows="#{bindings.FileUploadDownloadVO1.rangeSize}"
                              emptyText="#{bindings.FileUploadDownloadVO1.viewable ? 'No data to display.' : 'Access Denied.'}"
                              rowBandingInterval="0"
                              selectedRowKeys="#{bindings.FileUploadDownloadVO1.collectionModel.selectedRow}"
                              selectionListener="#{bindings.FileUploadDownloadVO1.collectionModel.makeCurrent}"
                              rowSelection="single" fetchSize="#{bindings.FileUploadDownloadVO1.rangeSize}" id="t2"
                              columnStretching="multiple">
                        <af:column headerText="#{bindings.FileUploadDownloadVO1.hints.FileName.label}" id="c1"
                                   width="300">
                            <af:outputText value="#{row.FileName}"
                                           shortDesc="#{bindings.FileUploadDownloadVO1.hints.FileName.tooltip}"
                                           id="ot1"/>
                        </af:column>
                        <af:column headerText="#{bindings.FileUploadDownloadVO1.hints.FilePath.label}" id="c2"
                                   width="400">
                            <af:outputText value="#{row.FilePath}"
                                           shortDesc="#{bindings.FileUploadDownloadVO1.hints.FilePath.tooltip}" id="ot2"
                                           binding="#{pageFlowScope.FileUploadDownloadBean.filePathBinding}"/>
                        </af:column>
                        <af:column id="c3">
                            <af:link text="Download" id="l1">
                                <af:fileDownloadActionListener filename="#{row.bindings.FileName.inputValue}"
                                                               method="#{pageFlowScope.FileUploadDownloadBean.downloadFileListener}"/>
                            </af:link>
                        </af:column>
                    </af:table>
                </af:panelCollection>
            </af:form>
        </af:document>
    </f:view>
</jsp:root>

And, the complete code for the FileUploadDownloadBean.java file is shown below.

package susantotech.com;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.faces.context.FacesContext;
import javax.faces.event.ValueChangeEvent;

import oracle.adf.model.BindingContext;
import oracle.adf.view.rich.component.rich.output.RichOutputText;
import oracle.adf.view.rich.util.ResetUtils;

import oracle.binding.BindingContainer;
import oracle.binding.OperationBinding;

import org.apache.myfaces.trinidad.model.UploadedFile;

public class FileUploadDownloadBean {
    private RichOutputText filePathBinding;

    public void setFilePathBinding(RichOutputText filePathBinding) {
        this.filePathBinding = filePathBinding;
    }

    public RichOutputText getFilePathBinding() {
        return filePathBinding;
    }

    public FileUploadDownloadBean() {
    }

    public void browseAndUploadFileVCE(ValueChangeEvent vce) {
        if (vce.getNewValue() != null) {
            UploadedFile fileVal = (UploadedFile) vce.getNewValue();
            String path = uploadFile(fileVal);
            System.out.println(fileVal.getContentType());
            OperationBinding ob = executeOperation("setFileData");
            ob.getParamsMap().put("name", fileVal.getFilename());
            ob.getParamsMap().put("path", path);
            ob.getParamsMap().put("contTyp", fileVal.getContentType());
            ob.execute();
            ResetUtils.reset(vce.getComponent());
        }
    }

    private String uploadFile(UploadedFile file) {
        UploadedFile myfile = file;
        String path = null;
        if (myfile == null) {
        } else {
            path = "C://Users//Susanto//Desktop//MyFolder//" + 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) {
                ex.printStackTrace();
            } finally {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return path;
    }

    public BindingContainer getBindingsCont() {
        return BindingContext.getCurrent().getCurrentBindingsEntry();
    }

    public OperationBinding executeOperation(String operation) {
        OperationBinding createParam = getBindingsCont().getOperationBinding(operation);
        return createParam;

    }

    public void downloadFileListener(FacesContext facesContext, OutputStream outputStream) throws IOException {
        File filed = new File(filePathBinding.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();
    }
}

Please add setFileData in the Bindings and Executables.

Save all and run the application. Thus, the ran application is shown below:

Once we Browse and Upload few of the files the screen will look like below:

Once we query the file_upload_download table in the Oracle Database, we can see the data as below:

And, the actual files are getting loaded in the Absolute Server Path that we have defined which is C:\Users\Susanto\Desktop\MyFolder as shown below.

Now to download the already uploaded file, we can click on the Download link in the table. And with that, the corresponding file will get downloaded against which we have clicked the Download link.

As we have click on the Download links of both the rows one after another, hence both the files got downloaded as shown below.

Hence, the solution to our requirement.

If you like the post please comment, share, and do join me on Facebook. Please subscribe to my YouTube Channel for video tutorials.

Thanks & Regards,
Susanto Paul

 530 total views,  1 views today

By Susanto Paul

Susanto is an Oracle ACE, a qualified MCA, MBA, and a highly-skilled Senior Oracle Specialist. He is an enthusiastic Blogger and YouTuber who helps learners to solve their complex problems more efficiently. He has 9+ years of experience in multiple technologies like AWS, Oracle ADF, Oracle APEX, Oracle JET, Oracle VBCS, Oracle IDCS, Oracle PL/SQL, Oracle Integration Cloud, Java, JDBC, Servlets, JSP, Spring, Hibernate, HTML5, CSS3, JavaScript, TypeScript, NodesJS, Angular, MySQL, Oracle WebLogic Server, JUnit, JMeter, Selenium Web Driver, etc. He is a certified: Oracle Certified Professional Java SE 6 Programmer, Oracle ADF 11g Certified Implementation Specialist, Oracle Cloud Platform Application Integration 2020 Certified Specialist, Oracle Cloud Infrastructure Foundations 2020 Certified Associate, and Oracle Cloud Infrastructure Developer 2020 Certified Associate

Leave a Reply

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