How do I upload file to FTP server?

This example demonstrate how to upload file to FTP server.

package org.kodejava.example.commons.net;

import org.apache.commons.net.ftp.FTPClient;
import java.io.FileInputStream;
import java.io.IOException;

public class FileUploadDemo {
    public static void main(String[] args) {
        FTPClient client = new FTPClient();
        FileInputStream fis = null;

        try {
            client.connect("ftp.domain.com");
            client.login("admin", "secret");

            //
            // Create an InputStream of the file to be uploaded
            //
            String filename = "Touch.dat";
            fis = new FileInputStream(filename);

            //
            // Store file to server
            //
            client.storeFile(filename, fis);
            client.logout();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fis != null) {
                    fis.close();
                }
                client.disconnect();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Wayan Saryada

I am a programmer, a runner, an open water diver and currently living in the island of Bali, Indonesia. If you need help on Java programming you can hire me on Fiverr.

5 Comments

  1. Hi,

    I am trying to upload a file of 3MB to FTP server using that code, but when I run it, it uploads only 40KB of the file. What to do?

    Thanks,
    Eden

    Reply
    • Hi Eden,

      Did you get any error message when uploading the file? You can try to call the client.getReplyCode() and client.getReplyString() to see if any error occurred while uploading. Just print the reply code and reply string message using System.out.println() after the client.storeFile() line.

      Reply
  2. I am getting below exception can you pls help me. Thanks in advance

    java.net.ConnectException: Connection timed out: connect
    at java.net.TwoStacksPlainSocketImpl.socketConnect(Native Method)
    at java.net.AbstractPlainSocketImpl.doConnect(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connectToAddress(Unknown Source)
    at java.net.AbstractPlainSocketImpl.connect(Unknown Source)
    at java.net.PlainSocketImpl.connect(Unknown Source)
    at java.net.SocksSocketImpl.connect(Unknown Source)
    at java.net.Socket.connect(Unknown Source)
    at org.apache.commons.net.ftp.FTPClient._openDataConnection_(FTPClient.java:762)
    at org.apache.commons.net.ftp.FTPClient._storeFile(FTPClient.java:565)
    at org.apache.commons.net.ftp.FTPClient.__storeFile(FTPClient.java:557)
    at org.apache.commons.net.ftp.FTPClient.storeFile(FTPClient.java:1795)
    at http://ftp.UploadFile.main(UploadFile.java:33)

    Reply

Leave a Comment.