To write Java code that uploads a file from local computer to a remote FTP server, the Apache Commons Net API is a preferred choice of developers. It has simple and comprehensive API that makes coding with upload files to FTP server with ease.

Table of Content:

    1. Apache Commons Net API for uploading files by FTP protocol
    2. The proper steps to upload a file
    3. Sample program code
    4. Download Apache Commons Net API
 

1. Apache Commons Net API for uploading files by FTP protocol

 The FTPClientclass provides six storeXXX()methods for transferring a local file to a remote server via FTP protocol:

    • boolean storeFile(String remote, InputStream local)
    • OutputStreamstoreFileStream(String remote)
    • boolean storeUniqueFile(InputStream local)
    • boolean storeUniqueFile(String remote, InputStream local)
    • OutputStreamstoreUniqueFileStream()
    • OutputStreamstoreUniqueFileStream(String remote)
Sounds too much? What is the difference among these methods? When to use which one? Well, they can be categorized by the following means:

    •           Store files by providing an InputStream of the local file (those methods which have an InputStream as a parameter). This type of methods can be used when we don’t care how the bytes are transferred from the local file to the remote one, just let the system done the ins and outs.
    •           Store files by writing to an OutputStream of the connection (those methods which return an OutputStream). This type of methods is needed when we want to control how the bytes are transferred, by writing our own code for reading bytes from the local file and write these bytes to the remote file through the OutputStream object. This can be useful if we want to show progress of the upload, by calculating how many bytes are transferred over total bytes needed.

The two ways above can be used in combination with:

    •           Name the remote file explicitly (those methods which accept a String parameter called remote).
    •           Let the server names the remote file with a unique name (those methods which do not have a String parameter).
Despite somewhat intricate of the storeXXX() methods, there are only two methods which are mostly used in practice, they are:

    • boolean storeFile(String remote, InputStream local)
    • OutputStreamstoreFileStream(String remote)
Besides the storeXXX() methods, there are also two other ones need to be invoked before and after a file transfer:

    •           boolean setFileType(int fileType): determines which file type, either FTP.ASCII_FILE_TYPE or FTP.BINARY_FILE_TYPE, is used for file transfer. The default type is ASCII (plain text file), but it should be set to binary type in order to work with any files. This method must be called before a file transfer starts.
    •           boolean completePendingCommand():This method should be called after file transfer finishes, to complete the transaction entirely. It would return true if successfully completed, or false otherwise. We should check return value of this method to ensure the upload is actually successful. However, this method may not be necessary for some of storeXXX() methods.
IMPORTANCES: By default, the FTP protocol establishes a data connection by opening a port on the client and allows the server connecting to this port. This is called local active mode, but it is usually blocked by firewall so the file transfer may not work. Fortunately, the FTP protocol has another mode, local passive mode, in which a data connection is made by opening a port on the server for the client to connect – and this is not blocked by firewall.

So it is recommended to switch to local passive mode before transferring data, by invoking the method enterLocalPassiveMode() of the FTPClient class.



 

2. The proper steps to upload a file to FTP server

 To properly write code to upload files to a FTP server using Apache Commons Net API, the following steps should be followed:

    •           Connect and login to the server.
    •           Enter local passive mode for data connection.
    •           Set file type to be transferred to binary.
    •           Create an InputStream for the local file.
    •           Construct path of the remote file on the server. The path can be absolute or relative to the current working directory.
    •           Call one of the storeXXX()methods to begin file transfer. There are two scenarios:
      •       Using an InputStream-based approach: this is the simplest way, since we let the system does the ins and outs. There is no additional code, just passing the InputStream object into the appropriate method, such as storeFile(String remote, InputStream local) method.
      •       Using an OutputStream-based approach: this is more complex way, but more control. Typically we have to write some code that reads bytes from the InputStream of the local file and writes those bytes into the OutputStream which is returned by the storeXXX() method, such as storeFileStream(String remote) method.
    •           Close the opened InputStream and OutputStream.
    •           Call completePendingCommand() method to complete transaction.
    •           Logout and disconnect from the server.
NOTES: we should check return value of the storeXXX() and completePendingCommand() method to ensure the upload is completed successfully.

 

3. Java FTP File Upload Sample program code

 The following sample program demonstrates uploading local files to a FTP server using these two methods:

    • boolean storeFile(String remote, InputStream local)
    • OutputStreamstoreFileStream(String remote)
After the storeFile() method, it is not necessary to call the completePendingCommand() method. Here is the full source code:

import java.io.File;
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;

/**
 * A program that demonstrates how to upload files from local computer
 * to a remote FTP server using Apache Commons Net API.
 * @author www.codejava.net
 */
public class FTPUploadFileDemo {

	public static void main(String[] args) {
		String server = "www.myserver.com";
		int port = 21;
		String user = "user";
		String pass = "pass";

		FTPClient ftpClient = new FTPClient();
		try {

			ftpClient.connect(server, port);
			ftpClient.login(user, pass);
			ftpClient.enterLocalPassiveMode();

			ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

			// APPROACH #1: uploads first file using an InputStream
			File firstLocalFile = new File("D:/Test/Projects.zip");

			String firstRemoteFile = "Projects.zip";
			InputStream inputStream = new FileInputStream(firstLocalFile);

			System.out.println("Start uploading first file");
			boolean done = ftpClient.storeFile(firstRemoteFile, inputStream);
			inputStream.close();
			if (done) {
				System.out.println("The first file is uploaded successfully.");
			}

			// APPROACH #2: uploads second file using an OutputStream
			File secondLocalFile = new File("E:/Test/Report.doc");
			String secondRemoteFile = "test/Report.doc";
			inputStream = new FileInputStream(secondLocalFile);

			System.out.println("Start uploading second file");
			OutputStream outputStream = ftpClient.storeFileStream(secondRemoteFile);
	        byte[] bytesIn = new byte[4096];
	        int read = 0;

	        while ((read = inputStream.read(bytesIn)) != -1) {
	        	outputStream.write(bytesIn, 0, read);
	        }
	        inputStream.close();
	        outputStream.close();

	        boolean completed = ftpClient.completePendingCommand();
			if (completed) {
				System.out.println("The second file is uploaded successfully.");
			}

		} 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();
			}
		}
	}

}
To work with Apache Commons Net API, the commons-net-VERSION.jar file must be added to the classpath. The jar file can be picked up from within a zip distribution which can be downloaded from http://commons.apache.org/net/download_net.cgi

 

Related Java FTP File Upload Tutorials:

 

Other Java File Upload Tutorials:

 

Other Java FTP Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.



Attachments:
Download this file (FTPUploadFileDemo.java)FTPUploadFileDemo.java[Sample program for uploading files to FTP server]2 kB

Add comment

   


Comments 

#58ahmed farghly thabet2021-03-01 05:23
good work mr.Nam Ha Minh
Quote
#57venkat2020-10-21 06:06
hi I am verym much impressed with this code
Quote
#56Boris Maidana2020-08-19 15:46
Excellent you are a great master!
Thank you a lot
Quote
#55Umesh2020-04-13 08:23
Can you please publish the FTPServer example?
Quote
#54Foodie Sapien2020-02-11 03:49
public static Session setupConnection(String user, String host, int port, String pass) throws JSchException {
JSch jsch = new JSch();
Session session = jsch.getSession(user, host, port);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(pass);
session.connect();
System.out.println("Connection established.");
System.out.println("Creating SFTP Channel.");
return session;
}
Quote