Java FTP Client Upload Example – Apache Commons Net

Filed Under: Java

Java FTP Client is used to upload files to FTP server. Recently I was working in a web project where I had to upload a lot of images to the FTP server. Few days back, I wrote a program to resize image in java. My actual program was to resize all the images in a directory and then upload to FTP server using Apache Commons Net API.

Java FTP Client Example

Java FTPClient Example, Java FTP Upload

Here I am providing a Java FTP client program to upload files to FTP server using Apache Commons Net API.


package com.journaldev.inheritance;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;

import org.apache.commons.net.PrintCommandListener;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPReply;

public class FTPUploader {
	
	FTPClient ftp = null;
	
	public FTPUploader(String host, String user, String pwd) throws Exception{
		ftp = new FTPClient();
		ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
		int reply;
		ftp.connect(host);
		reply = ftp.getReplyCode();
		if (!FTPReply.isPositiveCompletion(reply)) {
			ftp.disconnect();
			throw new Exception("Exception in connecting to FTP Server");
		}
		ftp.login(user, pwd);
		ftp.setFileType(FTP.BINARY_FILE_TYPE);
		ftp.enterLocalPassiveMode();
	}
	public void uploadFile(String localFileFullName, String fileName, String hostDir)
			throws Exception {
		try(InputStream input = new FileInputStream(new File(localFileFullName))){
		this.ftp.storeFile(hostDir + fileName, input);
		}
	}

	public void disconnect(){
		if (this.ftp.isConnected()) {
			try {
				this.ftp.logout();
				this.ftp.disconnect();
			} catch (IOException f) {
				// do nothing as file is already saved to server
			}
		}
	}
	public static void main(String[] args) throws Exception {
		System.out.println("Start");
		FTPUploader ftpUploader = new FTPUploader("ftp.journaldev.com", "ftpUser", "ftpPassword");
		//FTP server path is relative. So if FTP account HOME directory is "/home/pankaj/public_html/" and you need to upload 
		// files to "/home/pankaj/public_html/wp-content/uploads/image2/", you should pass directory parameter as "/wp-content/uploads/image2/"
		ftpUploader.uploadFile("D:\\Pankaj\\images\\MyImage.png", "image.png", "/wp-content/uploads/image2/");
		ftpUploader.disconnect();
		System.out.println("Done");
	}

}

You can use the above program to connect to an FTP server and then upload files to the server. Make sure you provide FTP Host, user, and password details correctly in the program. You can get these details when you create an FTP user.

The other important point to note is the server directory location. It’s relative to the FTP user home directory. Also, once you are done with uploading all the files, close the connection to the server and release resources.

You can find more core java examples from our GitHub Repository.

Comments

  1. dinesh says:

    Thanks for the example.

    I want to upload a file from jsp page how ca i achieve that using jsp? when the user browse the file and click on submit it will be stored in ftp server . how can i do that?

    Thanks in advance

    1. Nasry says:

      You can do this by writing java code and some jsp tags you can use jstl its easier to work with 🙂

  2. prem says:

    can anyone explian…?

    Start
    220———- Welcome to Pure-FTPd [privsep] [TLS] ———-
    220-You are user number 1 of 50 allowed.
    220-Local time is now 07:13. Server port: 21.
    220-This is a private system – No anonymous login
    220-IPv6 connections are also welcome on this server.
    220 You will be disconnected after 15 minutes of inactivity.
    USER ftpUser
    331 User ftpUser OK. Password required
    PASS ftpPassword
    530 Login authentication failed
    TYPE I
    200 TYPE is now 8-bit binary
    PASV
    530 You aren’t logged in
    QUIT
    221-Goodbye. You uploaded 0 and downloaded 0 kbytes.
    221 Logout.
    Done

    1. Paul says:

      Password is obviously wrong.

  3. jyoti says:

    Hi Pankaj,
    i used this code but at time of ftp . login(user, pwd); org.apache.commons.net.ftp.FTPConnectionClosedException: FTP response 421 received. Server closed connection. exception occur …dont know what happened….plz help

  4. sofiya says:

    hi pankaj

    Thanks for this informative post. Actually when am trying this program from source Linux machine to Destination Windows machine this program is hanging at start line only…like connect and at login its hanging . and program is not coming out. But when i do normal ftp commands from terminal those are working. but program wise its not working.

  5. Anshul Verma says:

    Start
    220———- Welcome to Pure-FTPd [privsep] [TLS] ———-
    220-You are user number 1 of 150 allowed.
    220-Local time is now 09:44. Server port: 21.
    220-This is a private system – No anonymous login
    220-IPv6 connections are also welcome on this server.
    220 You will be disconnected after 5 minutes of inactivity.
    USER anshul@hikejabalpur.com
    421 Sorry, cleartext sessions are not accepted on this server.
    Please reconnect using SSL/TLS security mechanisms.
    Exception in thread “main” org.apache.commons.net.ftp.FTPConnectionClosedException: FTP response 421 received. Server closed connection.
    at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:360)
    at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:290)
    at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:474)
    at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:547)
    at org.apache.commons.net.ftp.FTP.user(FTP.java:693)
    at org.apache.commons.net.ftp.FTPClient.login(FTPClient.java:872)
    at javaapplication1.FTPUploader.(FTPUploader.java:33)
    at javaapplication1.FTPUploader.main(FTPUploader.java:56)
    Java Result: 1

  6. Himanshu says:

    Hi Pankaj Sir,

    I am Use above code File Upload on FTP Server, I am confuse at FtpUploader.uploadFile. I have no ftp path mean my FTP drive have have no folder there . how can specify path there. Please reply fast sir

    1. Himanshu says:

      It’s working Fine

  7. ramesh Anem says:

    Hi pankaj,I am using as it is code regarding file upload but file not upladed its showing the console message 553 Could not create file what is the reason

    but logged in sucsses fully..where its getting prpb not finding please replay ASAP…..

  8. shaon says:

    thanks pankaj, its work !!!,, Your site is very useful.
    thanks again for sharing!

  9. Ram Mahesh says:

    What are the possible issues for IOException during file copy. I get IOException at storefile line in the FTP Upload Example.

  10. shruti says:

    Hello Pankaj,

    Thanks for sharing the article. Its of great help.

    I used your code and i am able to make a connection with the application. But i am unable to login as it says that the incorrect password.
    Although if i try to login via FTP client -“Filezilla” it works fine.

    The console output is:
    Start
    220 (vsFTPd 2.0.5)
    USER shrshrivastava
    331 Please specify the password.
    PASS Axway@1234
    530 Login incorrect.
    TYPE I
    530 Please login with USER and PASS.
    QUIT
    221 Goodbye.
    Done

  11. sanjeet says:

    Hi,pankaj i run the FTPUploader program with ip address which is in my intranet.The program give erro connectio refuse

    i provide IP :192.168.1.132
    username and password.

    pls help i want to upload file to the another computer in my network.

    is there need of writing other program for FTPServer seprately

    thanks

  12. Ram Mahesh Kumar says:

    I use the same apache commons ftp jar file. When i run this as a web application hosted on a server, there is some inconsistency. I get 451 error code stating that another command is pending. Can you help me in resolving this issue. I have not changed any part of your code. First few uploads are going on well, then this error occurs. Kindly help me.

  13. Ricardo V. Silva says:

    Hey, Pankaj
    I’m having this weird behaviour: the file I upload is never stored complete in the server. I mean there are always a few bytes missing. How can I make sure the file I uploaded is integrate and properly stored?

    1. Pankaj says:

      Are you trying to upload very huge file? Please check FTP logs in the server for any possible errors.

  14. Kotesh says:

    Hi
    pls check the below issue.
    Exception in thread “main” java.lang.SecurityException: Signers of ‘org.apache.commons.net.PrintCommandListener’ do not match signers of other classes in package
    at java.lang.ClassLoader.checkPackageSigners(ClassLoader.java:322)
    at java.lang.ClassLoader.defineClass(ClassLoader.java:264)
    at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:69)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:529)
    at java.net.URLClassLoader.defineClass(URLClassLoader.java:440)
    at java.net.URLClassLoader.access$300(URLClassLoader.java:68)
    at java.net.URLClassLoader$ClassFinder.run(URLClassLoader.java:1027)
    at java.security.AccessController.doPrivileged(AccessController.java:284)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:418)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:653)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:346)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:619)
    at com.java.ust.skillport.report.Ftp.FTPUploader.(FTPUploader.java:21)
    at com.java.ust.skillport.report.Ftp.FTPUploader.main(FTPUploader.java:57)

    1. Pankaj says:

      This issue can come when classes are getting loaded from multiple jar files, please check your build path if multiple jar files have PrintCommandListener class?

      1. Kotesh says:

        No, in my build path having only one PrintCommandListener class

        Here i am attaching the code::


        import java.io.File;
        import java.io.FileInputStream;
        import java.io.IOException;
        import java.io.InputStream;
        import java.io.PrintWriter;
        import java.util.concurrent.ExecutionException;

        //import org.apache.commons.net.PrintCommandListener;
        import org.apache.commons.net.PrintCommandListener;
        import org.apache.commons.net.ftp.FTP;
        import org.apache.commons.net.ftp.FTPClient;
        import org.apache.commons.net.ftp.FTPReply;

        public class FTPUploader {

        FTPClient ftp = null;

        public FTPUploader(String host, String user, String pwd) throws Exception{
        ftp = new FTPClient();
        ftp.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
        int reply;
        ftp.connect(host);
        reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
        ftp.disconnect();
        throw new Exception("Exception in connecting to FTP Server");
        }
        ftp.login(user, pwd);
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        ftp.enterLocalPassiveMode();
        }
        public void uploadFile(String localFileFullName, String fileName, String hostDir)
        throws Exception {
        try {
        InputStream input = new FileInputStream(new File(localFileFullName));

        this.ftp.storeFile(hostDir + fileName, input);
        }
        catch(Exception e){

        }
        }

        public void disconnect(){
        if (this.ftp.isConnected()) {
        try {
        this.ftp.logout();
        this.ftp.disconnect();
        } catch (IOException f) {
        // do nothing as file is already saved to server
        }
        }
        }
        public static void main(String[] args) throws Exception {
        System.out.println("Start");
        FTPUploader ftpUploader = new FTPUploader("sftp.p.com", "user", "Pwd");

        //FTP server path is relative. So if FTP account HOME directory is "/home/pankaj/public_html/" and you need to upload
        // files to "/home/pankaj/public_html/wp-content/uploads/image2/", you should pass directory parameter as "/wp-content/uploads/image2/"
        ftpUploader.uploadFile("C:\\Users\\Kotesh\\Desktop\\Skills\\uploadedFile.txt", "uploadedFile.txt", "/HOME/DBDUMP/");
        ftpUploader.disconnect();
        System.out.println("Done");
        }

        }

        1. Pankaj says:

          Its not the problem with the code, clean the project and try to run it from command line including only the jar files you need in the classpath. I believe there are some other jars in the classpath causing the issue.

  15. Phil says:

    Hello. Thanks for sharing this example. I am lost on the try(InputStream input = new FileInputStream(new File(localFileFullName))) in the uploadFile method. I’ve never seen a try ( ) before. What is that? Is it some kind of anonymous inner class? Thank you.

      1. Phil says:

        Thanks for the quick reply. I can see I have some reading to do. Thanks again

  16. Sergio says:

    Thanks, great explanation and very clear concepts, I find very useful

  17. Santo says:

    Very good information. Lucky me I came across your site by chance (stumbleupon).

    I have bookmarked it for later!

  18. zbarciog says:

    I receive a strange error, when I am trying to run the program in vmware using windows 7, using both internet connection(bridge or NAT). I do not understand why on the host is working, and in virtual no!
    This is the error:

    230-OK. Current restricted directory is /
    230-12 files used (0%) – authorized: 10000 files
    230 5394 Kbytes used (0%) – authorized: 1536000 Kb
    TYPE I
    200 TYPE is now 8-bit binary
    PASV
    Exception in thread “main” java.net.SocketException: Permission denied: recv failed
    at java.net.SocketInputStream.socketRead0(Native Method)
    at java.net.SocketInputStream.read(Unknown Source)
    at java.net.SocketInputStream.read(Unknown Source)
    at sun.nio.cs.StreamDecoder.readBytes(Unknown Source)
    at sun.nio.cs.StreamDecoder.implRead(Unknown Source)
    at sun.nio.cs.StreamDecoder.read(Unknown Source)
    at java.io.InputStreamReader.read(Unknown Source)
    at java.io.BufferedReader.fill(Unknown Source)
    at java.io.BufferedReader.read(Unknown Source)
    at org.apache.commons.net.io.CRLFLineReader.readLine(CRLFLineReader.java:58)
    at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:314)
    at org.apache.commons.net.ftp.FTP.__getReply(FTP.java:294)
    at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:483)
    at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:608)
    at org.apache.commons.net.ftp.FTP.sendCommand(FTP.java:582)
    at org.apache.commons.net.ftp.FTP.pasv(FTP.java:1007)
    at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:869)
    at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:633)
    at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:624)
    at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1976)
    at model.FTPUploader.uploadFile(FTPUploader.java:35)
    at model.FTPUploader.main(FTPUploader.java:59)

    1. zbarciog says:

      I user also Windows 7 as host

    2. Pankaj says:

      This seems related to the permissions VMWare user has to use internet or to open a socket connection.

      1. zbarciog says:

        Same problem in VirtualBox, but here the program does not return any error message, just stops after “PASV”. The only one solution that i find it: use the host :))
        @Pankaj – thx for the code and keep the good work!

  19. Nilesh says:

    Hey pankaj thanks it was helpful and useful.

    1. Pankaj says:

      Thanks Nilesh for liking it.

  20. Revathi says:

    Hi.. Im getting the following exception exactly at ftpClient.StoreFile(..,..)
    18:07:33,252 INFO [STDOUT] PASV
    18:07:33,341 INFO [STDOUT] 227 Entering Passive Mode (192,168,33,17,104,34)
    18:08:38,768 INFO [STDOUT] Error: Connection timed out: connect
    18:08:39,516 ERROR [STDERR] java.net.ConnectException: Connection timed out: connect
    18:08:39,517 ERROR [STDERR] at java.net.PlainSocketImpl.socketConnect(Native Method)
    18:08:39,518 ERROR [STDERR] at java.net.PlainSocketImpl.doConnect(PlainSocketImpl.java:333)
    18:08:39,518 ERROR [STDERR] at java.net.PlainSocketImpl.connectToAddress(PlainSocketImpl.java:195)
    18:08:39,519 ERROR [STDERR] at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:182)
    18:08:39,520 ERROR [STDERR] at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:366)
    18:08:39,521 ERROR [STDERR] at java.net.Socket.connect(Socket.java:519)
    18:08:39,522 ERROR [STDERR] at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:825)
    18:08:39,523 ERROR [STDERR] at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:602)
    18:08:39,524 ERROR [STDERR] at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:593)
    18:08:39,524 ERROR [STDERR] at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1903)
    18:08:39,525 ERROR [STDERR] at com.tcs.servlet.UploadFileServlet.doPost(UploadFileServlet.java:171)
    18:08:39,526 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:710)
    18:08:39,527 ERROR [STDERR] at javax.servlet.http.HttpServlet.service(HttpServlet.java:803)
    18:08:39,528 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
    18:08:39,529 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    18:08:39,532 ERROR [STDERR] at org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:96)
    18:08:39,533 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:235)
    18:08:39,534 ERROR [STDERR] at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
    18:08:39,535 ERROR [STDERR] at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:230)
    18:08:39,536 ERROR [STDERR] at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
    18:08:39,537 ERROR [STDERR] at org.jboss.web.tomcat.security.SecurityAssociationValve.invoke(SecurityAssociationValve.java:182)
    18:08:39,538 ERROR [STDERR] at org.jboss.web.tomcat.security.JaccContextValve.invoke(JaccContextValve.java:84)
    18:08:39,539 ERROR [STDERR] at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
    18:08:39,539 ERROR [STDERR] at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
    18:08:39,540 ERROR [STDERR] at org.josso.tc55.agent.SSOAgentValve.invoke(SSOAgentValve.java:274)
    18:08:39,541 ERROR [STDERR] at org.jboss.web.tomcat.service.jca.CachedConnectionValve.invoke(CachedConnectionValve.java:157)
    18:08:39,542 ERROR [STDERR] at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
    18:08:39,543 ERROR [STDERR] at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:262)
    18:08:39,544 ERROR [STDERR] at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:844)
    18:08:39,545 ERROR [STDERR] at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:583)
    18:08:39,546 ERROR [STDERR] at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:446)
    18:08:39,546 ERROR [STDERR] at java.lang.Thread.run(Thread.java:595)
    18:08:40,717 INFO [STDOUT] QUIT

    Kindly help me out. I tried using ftpClient.enterLocalPassiveMode(); . Still the issue remains.

    1. Pankaj says:

      I am not sure what the problem is, can you check that FTP is working fine using command line?

  21. Java Web Hosting says:

    Everything is very open with a very clear clarification of the issues.

    It was really informative. Your site is very useful.
    Many thanks for sharing!

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages