Java FTP file upload tutorial and example
- Details
- Written by Nam Ha Minh
- Last Updated on 20 July 2019   |   Print Email
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)
- 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).
- boolean storeFile(String remote, InputStream local)
- OutputStreamstoreFileStream(String remote)
- 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.
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.
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)
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:
- Upload files to FTP server using URLConnection class
- How to upload a directory to a FTP server
- Swing application to upload files to FTP server with progress bar
Other Java File Upload Tutorials:
- Java Servlet File Upload Example
- Spring MVC File Upload Tutorial
- Struts File Upload Example
- Java Upload files to database (Servlet + JSP + MySQL)
Other Java FTP Tutorials:
- Connect and login to a FTP server
- Java FTP create directory example
- Java FTP example - Change working directory
- Java FTP list files and directories example
- Java FTP file download tutorial and example
- Java FTP delete file example
- Java FTP example - Search for files and directories
Comments
Thank you a lot
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;
}