ADF: How to upload file in FTP server using apache common net API?

ADF: How to upload file in FTP server using apache common net API?

This post is about How to upload file in FTP Server using apache common net API(Download here). ADF faces inputFile component allows user to upload file from browser. So we only need to connect to FTP server and upload file. Following are steps-

Sample Code
  1. Add inputFile component from component palette to page.
  
        
      
 

Make sure usesUpload property of form is true. On valueChageListener event of inputFile, call a method(uploadFile).

  1. Get uploaded file instance in uploadFile method as follows-
       
 UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();
  1. To make connection with FTP server you will need server credentials like Server Host, port (default 21), user name and password.
      
  public void uploadFile(ValueChangeEvent valueChangeEvent) {

        //Get Uploaded file
        UploadedFile file = (UploadedFile)valueChangeEvent.getNewValue();

        //FTP server credential
        String server = "172.31.33.11";
        int port = 21;
        String user = "myserver";
        String pass = "test@123";
        //Create FTP Client instance
        FTPClient ftpClient = new FTPClient();
        try {
            //Connect to server
            ftpClient.connect(server, port);
            // Do login
            ftpClient.login(user, pass);
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);


            if (ftpClient.isConnected()) {
                InputStream in = file.getInputStream();
                System.out.println("Start uploading first file");
                boolean done = ftpClient.storeFile(file.getFilename(), in);
                System.out.println(ftpClient.getReplyCode());
                System.out.println(ftpClient.getReplyString());
                if (done) {
                    System.out.println("The  file is uploaded successfully.");
                }

                in.close();
            }
        } catch (IOException ex) {
            System.out.println("Error: " + ex.getMessage());
            ex.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
    }

About Manish Pandey

Manish is a Project Leader at Jagran Prakashan Ltd, focused on Jdeveloper Fusion Web Application(specifically Oracle ADF). He shares his knowledge through the OTN Jdev/ADF Forum. He has written more than 50 article about Oracle ADF and Jdeveloper.

Leave a Reply