com.tapontikes.java.doUpload.java Source code

Java tutorial

Introduction

Here is the source code for com.tapontikes.java.doUpload.java

Source

package com.tapontikes.java;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import javax.swing.JOptionPane;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
/**
 *
 * @author tom
 */
public class doUpload {

    private final String _host;
    private final String _user;
    private final String _pass;
    private final String _path;
    private String _done;
    private String remote_file;
    private File local_file;
    private InputStream input;
    boolean complete;
    private final FTPClient _ftp;

    public doUpload(String user, String pass, String path, String host) {

        _user = user;
        _pass = pass;
        _path = path;
        _host = host;
        _ftp = new FTPClient();

    }

    public String uploadSingleFile() {

        try {

            ftpInitiate();

            local_file = new File(_path);
            remote_file = "public_html/" + local_file.getName();

            checkExist();

            input = new FileInputStream(local_file);

            complete = _ftp.storeFile(remote_file, input);

            input.close();

            _done = isComplete();

        } catch (IOException ex) {
            disconnect();
            return ex.getLocalizedMessage();

        }

        return _done;

    }

    public String uploadDirectory() {

        return null;
    }

    public void ftpInitiate() throws IOException {

        _ftp.setConnectTimeout(30000);
        _ftp.connect(_host);
        _ftp.login(_user, _pass);
        _ftp.enterLocalActiveMode();
        _ftp.setFileType(FTP.BINARY_FILE_TYPE);

    }

    public void checkExist() throws IOException {

        _ftp.changeWorkingDirectory("/public_html");

        String[] files = _ftp.listNames();

        if (Arrays.asList(files).contains(local_file.getName())) {
            JOptionPane.showMessageDialog(null, local_file.getName() + " already exists on the server.", "Alert!",
                    JOptionPane.INFORMATION_MESSAGE);
            System.exit(0);
        }
        _ftp.changeWorkingDirectory("/");

    }

    public String isComplete() {

        if (complete) {

            disconnect();
            return "Upload has completed successfully";

        }

        disconnect();
        return "Upload Failed";

    }

    public void disconnect() {

        if (this._ftp.isConnected()) {
            try {
                this._ftp.logout();
                this._ftp.disconnect();
            } catch (IOException f) {
            }
        }
    }

}