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:

Sounds too much? What is the difference among these methods? When to use which one? Well, they can be categorized by the following means:

The two ways above can be used in combination with:

Despite somewhat intricate of the storeXXX() methods, there are only two methods which are mostly used in practice, they are:

Besides the storeXXX() methods, there are also two other ones need to be invoked before and after a file transfer:

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:

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:

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 started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



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