Search code examples
javaftpuploadftp-clientapache-commons-net

Java Apache FTP client - Resume broken upload


I need to implement resuming of upload in my FTP client, if something went wrong. ftp in the example below is Apache FTPClient.

public boolean upload(InputStream localFile, String remoteName, boolean createNew) {

    if (StringUtils.isBlank(remoteName)) {
        log.warn("Error while uploading file: localFile or remoteName is null");
        return false;
    }

    synchronized (this) {
        try {

            if (createNew) {
                return ftp.storeFile(remoteName, localFile);
            } else {
                return ftp.appendFile(remoteName, localFile); //todo is it right?
            }
        } catch (Exception ex) {
            log.error(ex.getMessage(), ex);
            return false;
        }
    }

}

So if ftp.storeFile crashes (not all bytes were sent e.g.), how can I continue uploading using the same InputStream?


Solution

    • reconnect your FTP session (if it was broken too);
    • test size of remote file to determine how many bytes made it all the way through to the remote disk (e.g. using FTPClient.mlistFile or SIZE command – See How to get info of an FTPFile);
    • seek the "input stream" back to that point (though InputStream does not support seeking, so you will have to use a different stream implementation – or reopen the InputStream and skip to the position);
    • call FTPClient.appendFile.