File upload on FTP server using Java

In this tutorial, let us learn about uploading files from your local computer to a remote FTP server in Java. The content covered, highlights the ease with which the files are uploaded on the server. The steps are mentioned as well as the information regarding the ‘Apache Commons Net API’ is discussed. And, last but never least, the source code which is the much-needed element of the content, required by the users, is provided.

As you may be aware – File Transfer Protocol is a standard network protocol for the transmission of files from the computer or local machine to the server and vice-versa. It works on the client-server architecture which establishes isolated connections for the control and transfer of data.

There are multiple libraries in Java using which the data could be uploaded on the server, but the preferred choice of the developers is to use the Apache Commons Net API  library; which provides an easy and comprehensive approach for the purpose.

Concept of File Upload on FTP Server using Java

So, the content which we will cover related to the concept is as follows:-

  1. The disburse steps for uploading a file on the server.
  2. Apache Commons Net API
  3. Sample program code
  4. Apache Commons Net API – Download

Let’s ponder over them one by one.

1. The disburse steps for uploading a file on the server.

The steps which can be easily followed to upload a file from the local machine to the remote FTP server using Java are mentioned below:-

  • Login and connect to the server.
  • The local passive mode must be entered for the data connection.
  • The type of the file must be set for transmission to binary mode.
  • InputStream must be created for the file.
  • The absolute or relative path must be constructed, for the current working directory.
  • To begin file transfer, one of the methods is called out of the store functions now, there could be two scenarios; based on InputStream and OutputStream.
  • Close the OutputStream and InputStream which were opened.
  • Invoke the completePendingCommand() method for terminating the successful complete transmission.
  • Ensure to Log out of the server and simultaneously disconnect from it.

NOTE: To ensure upload of the file successfully on the server completePendingCommand() method should be invoked and the value returned by one of the store functions must be validated.

2. Apache Commons Net API

In Java, we have a class related to FTP and ie. FTPClient class provides us with six different and unique store functions, which are really very useful for the transmission of a local file on the server using FTP. Lets’ grasp them, individually: –

  • storeFile(String remote, InputStream local) : boolean return type function.
  • storeFileStream(String remote): OutputStream return type function.
  • storeUniqueFile(InputStream local): boolean return type function.
  • storeUniqueFile(String remote, InputStream local) : boolean return type function.
  • storeUniqueFileStream(): OutputStream return type function.
  • storeUniqueFileStream(String remote): OutputStream return type function.

Halt! what? sounds too much? Isn’t it? Now, you must be thinking that what is the difference between them? When we have to use which function? Well, they can be explained as follows:-

         Streams for File Storage

  • Files can be stored by writing to an OutputStream of a connection: In other words, the methods which return an OutputStream object. Such methods are required when we are needed to write the code by ourselves to the remote file through the OutputStream object, and allow access to read the local file; then the bytes which are to be transferred are very well controlled. This is a useful approach when we want to demonstrate and record the progress of the upload.
  • Files can be stored by providing an Inputstream of the local file: In other words, the methods which could be used when the data transmission control is not to be either recorded or to be demonstrated anywhere. Moreover, the system performs its own set of input and output cycles to transfer the data from the local environment to the remote one.

The ways which are mentioned above can be associated effectively with:-

  • Explicit name declaration of the remote file, in other words, the methods which expect an argument called remote.
  • Implicit name declaration of the remote file, in other words, the server names the remote file with a unique name; which indirectly implies the methods which do not expect an argument.

Despite so many useful methods of store functions in FTPClient class, the methods which are mostly used in practicality are:-

  • boolean storeFile(String remote, InputStream local)
  • OutputStreamstoreFileStream(String remote)

The methods which are pivotal in data transmission procedure are discussed:-

  • boolean setFileType(int fileType): This function, determines the type of the file used for file transfer which could be either FTP.ASCII_FILE_TYPE OR FTP.BINARY_FILE_TYPE.
  • boolean completePendingCommand(): This method is invoked when the file transmission process is terminated. The function is a return type function and returns True if the file is successfully uploaded, otherwise, False is returned. But, this method is applicable to some store functions only.

IMPORTANT

There are two different techniques by which the connection between the client and the server could be established. And those techniques are explained as follows:-

  • Local Passive Mode: In this technique, the data connection is established when the port on the server is opened for the client to connect. And, the firewall allows access by not blocking the data transmission.
  • Local Active Mode: In this technique, the data connection is established when the port on the client is opened which allows the establishment of the connection on this port.

Hence, before transmission of the data, it is preferred to switch to local passive mode rather than the local active mode, by invoking the method enterLocalPassiveMode() of the FTPClient class.

3. Sample Java Program Code: file upload on FTP server

The sample program to explain and demonstrate the procedure to upload a file on FTP server using Java is as follows:-

package CodeSpeedy;

import java.io.*;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
 
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
 
public class FTPServer{
 
    public static void main(String[] args) {
        String servername = "www.uploadfile.com";
        int portnumber = 21;
        String user_string = "user";
        String pass_string = "pass";
 
        FTPServer ftpClient = new FTPServer();
        try {
 
            ftpClient.connect(servername, portnumber);
            ftpClient.login(user_string, pass_string);
            ftpClient.enterLocalPassiveMode();
 
            ftpClient.setFileType(FTPServer.BINARY_FILE_TYPE);
 
            // Method 1: Using InputStream
            File firstLocFile = new File("C:/Documents/Demo.zip");
 
            String firstRemFile = "Demo.zip";
            
            InputStream inputStream = new FileInputStream(firstLocFile);
 
            System.out.println("Initiate the upload process for the first file");
            
            boolean terminate = ftpClient.storeFile(firstRemFile, inputStream);
            
            inputStream.close();
            
            if (terminate) {
                System.out.println("The first file is uploaded on the FTP server successfully.");
            }
 
            // Method 2: Using OutputStream
            
            File secLocFile = new File("C:/Documents/Info.doc");
            
            String secRemFile = "Documents/Info.doc";
            
            inputStream = new FileInputStream(secLocFile);
 
            System.out.println("Initiate the upload process for the second file");
            
            OutputStream outputStream = ftpClient.storeFileStream(secRemFile);
            
            byte[] bytesInput = new byte[4096];
            
            int read_data = 0;
 
            while ((read_data = inputStream.read(bytesInput)) != -1) {
                outputStream.write(bytesInput, 0, read_data);
            }
            
            inputStream.close();
            outputStream.close();
 
            boolean completed = ftpClient.completePendingCommand();
            
            if (completed) {
                System.out.println("The second file is uploaded on the FTP server successfully.");
            }
 
        } catch (IOException e) {
            System.out.println("Error Occurred: " + e.getMessage());
            e.printStackTrace();
        } finally {
            try {
                if (ftpClient.isConnected()) {
                    ftpClient.logout();
                    ftpClient.disconnect();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 
}

If you want to use Apache Commons Net API then you have to add the commons-net-Version.jar file in the classpath; otherwise, the code will not execute properly.

The file can be downloaded from here,  http://commons.apache.org/proper/commons-net/download_net.cgi

Leave a Reply

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