Example usage for org.apache.commons.net.ftp FTPClient storeFile

List of usage examples for org.apache.commons.net.ftp FTPClient storeFile

Introduction

In this page you can find the example usage for org.apache.commons.net.ftp FTPClient storeFile.

Prototype

public boolean storeFile(String remote, InputStream local) throws IOException 

Source Link

Document

Stores a file on the server using the given name and taking input from the given InputStream.

Usage

From source file:com.unicomer.opos.inhouse.gface.ejb.impl.GfaceGuatefacturasControlFtpEjbLocalImpl.java

public void send(File[] archivos) {
    try {//from w ww .  ja  v a2 s.co  m
        HashMap<String, String> params = getFtpParams();
        FTPClient ftpClient = getFtpClient(params);
        BufferedInputStream buffIn = null;
        for (File actual : archivos) {
            //                String fileName = "PROCESOS_PARA_EL_IVA_VENTAS_UNICOMER.xlsx";
            buffIn = new BufferedInputStream(new FileInputStream(actual.getAbsolutePath()));//Ruta del archivo para enviar
            ftpClient.enterLocalPassiveMode();
            ftpClient.storeFile(params.get("remoteStoreFiles") + REMOTE_SEPARATOR + actual.getName(), buffIn);//Ruta completa de alojamiento en el FTP
            if (ftpClient.getReplyCode() == 226) {
                System.out.println("Archivo guardado exitosamente");
            } else {
                System.out.println("No se pudo guardar el archivo: " + actual.getName() + ", codigo:"
                        + ftpClient.getReplyCode());
            }
        }

        buffIn.close(); //Cerrar envio de archivos al FTP
        ftpClient.logout(); //Cerrar sesin
        ftpClient.disconnect();//Desconectarse del servidor
    } catch (Exception e) {
        System.out.println("Error: " + e.getMessage());
    }
}

From source file:com.globalsight.smartbox.util.FtpHelper.java

public boolean ftpStoreFile(String remoteFileName, File localFile) {
    FTPClient ftpClient = getFtpClient();
    if (ftpClient != null && ftpClient.isConnected()) {
        FileInputStream localFIS = null;
        try {/*from   www. j a v a  2s . c o m*/
            localFIS = new FileInputStream(localFile);
            return ftpClient.storeFile(remoteFileName, localFIS);
        } catch (IOException e) {
            LogUtil.fail("Store File Error: " + remoteFileName, e);
        } finally {
            try {
                localFIS.close();
            } catch (IOException e) {
                LogUtil.fail("Fail to close FileInputStream: " + localFile.getAbsolutePath(), e);
            }
            closeFtpClient(ftpClient);
        }
    }

    return false;
}

From source file:br.com.tiagods.util.FTPUpload.java

public boolean uploadFile(File arquivo, String novoNome) {
    FTPConfig cf = FTPConfig.getInstance();

    FTPClient ftp = new FTPClient();
    try {/*from  ww w.j  a v  a 2  s.co m*/
        ftp.connect(cf.getValue("host"), Integer.parseInt(cf.getValue("port")));
        ftp.login(cf.getValue("user"), cf.getValue("pass"));
        //ftp.connect(server,port);
        //ftp.login(user,pass);
        ftp.enterLocalPassiveMode();
        ftp.setFileType(FTP.BINARY_FILE_TYPE);
        boolean done;
        try (InputStream stream = new FileInputStream(arquivo)) {
            String remoteFile = novoNome;
            System.out.println("Start uploading first file");
            done = ftp.storeFile(cf.getValue("dirFTP") + "/" + remoteFile, stream);
            stream.close();
        }
        if (done) {
            JOptionPane.showMessageDialog(null, "Arquivo enviado com sucesso!");
            return true;
        }
        return false;
    } catch (IOException e) {
        System.out.println("Erro = " + e.getMessage());
        return false;
    } finally {
        try {
            if (ftp.isConnected()) {
                ftp.logout();
                ftp.disconnect();
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

From source file:net.paissad.jcamstream.utils.FTPUtils.java

/**
 * Stores a file on the server using the given name and taking input from
 * the given InputStream./*from w  ww. j  ava  2 s  . c om*/
 * <p>
 * <b>Note</b>: The InputStream is not closed ! Feel free or responsible to
 * close it (or not) after use.
 * </p>
 * 
 * @param remoteFileName
 *            - The name that will be given to the file onto the FTP server.
 * @param in
 *            - The stream to upload the FTP server.
 * @throws IOException
 * @throws FTPException
 */
public void uploadStream(String remoteFileName, InputStream in) throws IOException, FTPException {
    FTPClient client = this.getFtpClient();
    String errMsg;

    int filesize = in.available();
    client.allocate(filesize);
    String humanFileSize = CommonUtils.humanReadableByteCount(filesize, false);
    errMsg = "Unable to allocate the amount of size " + humanFileSize + " for the file " + remoteFileName;
    this.verifyReplyCode(errMsg);

    client.storeFile(remoteFileName, in);
    errMsg = "Unable to store the file " + remoteFileName + " to the server";
    this.verifyReplyCode(errMsg);
}

From source file:model.ProfilModel.java

public void uploadFoto(String path) {
    String server = "localhost";
    int port = 21;
    String user = "user1";
    String pass = "itsme";

    FTPClient ftpClient = new FTPClient();
    try {//from  ww  w  .j a va2 s.  c om

        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(path);

        String firstRemoteFile = this.user.getFoto();
        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.");
        }
        inputStream.close();

    } 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();
        }
    }
}

From source file:com.alexkasko.netty.ftp.FtpServerTest.java

@Test
public void test() throws IOException, InterruptedException {
    final DefaultCommandExecutionTemplate defaultCommandExecutionTemplate = new DefaultCommandExecutionTemplate(
            new ConsoleReceiver());
    EventLoopGroup bossGroup = new NioEventLoopGroup();
    EventLoopGroup workerGroup = new NioEventLoopGroup();
    ServerBootstrap b = new ServerBootstrap();
    b.group(bossGroup, workerGroup).channel(NioServerSocketChannel.class)
            .childHandler(new ChannelInitializer<SocketChannel>() {

                @Override/*from   w  w  w  . ja  v a 2  s.c  om*/
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipe = ch.pipeline();
                    pipe.addLast("decoder", new CrlfStringDecoder());
                    pipe.addLast("handler", new FtpServerHandler(defaultCommandExecutionTemplate));
                }

            });
    b.localAddress(2121).bind();
    FTPClient client = new FTPClient();
    //        https://issues.apache.org/jira/browse/NET-493

    client.setBufferSize(0);
    client.connect("127.0.0.1", 2121);
    assertEquals(230, client.user("anonymous"));

    // active
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    assertEquals("/", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.listFiles("/foo").length == 0);
    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    //  assertTrue(client.deleteFile("baz"));

    // passive
    assertTrue(client.setFileType(FTP.BINARY_FILE_TYPE));
    client.enterLocalPassiveMode();
    assertEquals("/foo", client.printWorkingDirectory());
    assertTrue(client.changeWorkingDirectory("/foo"));
    assertEquals("/foo", client.printWorkingDirectory());

    //TODO make a virtual filesystem that would work with directory
    //assertTrue(client.listFiles("/foo").length==1);

    assertTrue(client.storeFile("bar", new ByteArrayInputStream("content".getBytes())));
    assertTrue(client.rename("bar", "baz"));
    // client.deleteFile("baz");

    assertEquals(221, client.quit());
    try {
        client.noop();
        fail("Should throw exception");
    } catch (IOException e) {
        //expected;
    }

}

From source file:EscribirCorreo.java

private void SubirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_SubirActionPerformed
    //Codigo para subir archivo         
    String localfile = subir1Field.getText();
    String server = "51.254.137.26";
    String username = "proyecto";
    String password = "proyecto";
    String destinationfile = nombre;
    try {/*  w  ww.  j  a va  2s  .co m*/
        FTPClient ftp = new FTPClient();
        ftp.connect(server);
        if (!ftp.login(username, password)) {
            ftp.logout();
        }
        int reply = ftp.getReplyCode();
        if (!FTPReply.isPositiveCompletion(reply)) {
            ftp.disconnect();
        }
        InputStream in = new FileInputStream(localfile);
        ftp.setFileType(ftp.BINARY_FILE_TYPE);
        ftp.storeFile(destinationfile, in);
        JOptionPane.showMessageDialog(null, "Archivo subido correctamente", "Subido!",
                JOptionPane.INFORMATION_MESSAGE);
        if (archivos == null) {
            archivos = "http://51.254.137.26/proyecto/" + destinationfile;
        } else {
            archivos = archivos + "#http://51.254.137.26/proyecto/" + destinationfile;
        }
        in.close();
        ftp.logout();
        ftp.disconnect();

    } catch (Exception ex) {
        ex.printStackTrace();
    }

}

From source file:facturacion.ftp.FtpServer.java

public static int sendImgFile(String fileNameServer, String hostDirServer, InputStream localFile) {
    FTPClient ftpClient = new FTPClient();
    boolean success = false;
    BufferedInputStream buffIn = null;
    try {/*from   ww w  . j  a  v  a 2  s.  co m*/
        ftpClient.connect(Config.getInstance().getProperty(Config.ServerFtpToken),
                Integer.parseInt(Config.getInstance().getProperty(Config.PortFtpToken)));
        ftpClient.login(Config.getInstance().getProperty(Config.UserFtpToken),
                Config.getInstance().getProperty(Config.PassFtpToken));
        ftpClient.enterLocalPassiveMode();
        /*ftpClient.connect("127.0.0.1", 21);
          ftpClient.login("erpftp", "Tribut@2014");*/
        ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

        int reply = ftpClient.getReplyCode();

        System.out.println("Respuesta recibida de conexin FTP:" + reply);

        if (!FTPReply.isPositiveCompletion(reply)) {
            System.out.println("Imposible conectarse al servidor");
            return -1;
        }

        buffIn = new BufferedInputStream(localFile);//Ruta del archivo para enviar
        ftpClient.enterLocalPassiveMode();
        //crear directorio
        success = ftpClient.makeDirectory(hostDirServer);
        System.out.println("sucess 1 = " + success);
        success = ftpClient.makeDirectory(hostDirServer + "/img");
        System.out.println("sucess 233 = " + success);
        success = ftpClient.storeFile(hostDirServer + "/img/" + fileNameServer, buffIn);
        System.out.println("sucess 3 = " + success);
    } catch (IOException ex) {

    } finally {
        try {
            if (ftpClient.isConnected()) {
                buffIn.close(); //Cerrar envio de arcivos al FTP
                ftpClient.logout();
                ftpClient.disconnect();
            }
        } catch (IOException ex) {
            return -1;
            //ex.printStackTrace();
        }
    }
    return (success) ? 1 : 0;
}

From source file:com.geotrackin.gpslogger.senders.ftp.Ftp.java

public synchronized static boolean Upload(String server, String username, String password, String directory,
        int port, boolean useFtps, String protocol, boolean implicit, InputStream inputStream,
        String fileName) {/* w ww .j  av  a  2 s . co m*/
    FTPClient client = null;

    try {
        if (useFtps) {
            client = new FTPSClient(protocol, implicit);

            KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
            kmf.init(null, null);
            KeyManager km = kmf.getKeyManagers()[0];
            ((FTPSClient) client).setKeyManager(km);
        } else {
            client = new FTPClient();
        }

    } catch (Exception e) {
        tracer.error("Could not create FTP Client", e);
        return false;
    }

    try {
        tracer.debug("Connecting to FTP");
        client.connect(server, port);
        showServerReply(client);

        tracer.debug("Logging in to FTP server");
        if (client.login(username, password)) {
            client.enterLocalPassiveMode();
            showServerReply(client);

            tracer.debug("Uploading file to FTP server " + server);

            tracer.debug("Checking for FTP directory " + directory);
            FTPFile[] existingDirectory = client.listFiles(directory);
            showServerReply(client);

            if (existingDirectory.length <= 0) {
                tracer.debug("Attempting to create FTP directory " + directory);
                //client.makeDirectory(directory);
                ftpCreateDirectoryTree(client, directory);
                showServerReply(client);

            }

            client.changeWorkingDirectory(directory);
            boolean result = client.storeFile(fileName, inputStream);
            inputStream.close();
            showServerReply(client);
            if (result) {
                tracer.debug("Successfully FTPd file " + fileName);
            } else {
                tracer.debug("Failed to FTP file " + fileName);
                return false;
            }

        } else {
            tracer.debug("Could not log in to FTP server");
            return false;
        }

    } catch (Exception e) {
        tracer.error("Could not connect or upload to FTP server.", e);
        return false;
    } finally {
        try {
            tracer.debug("Logging out of FTP server");
            client.logout();
            showServerReply(client);

            tracer.debug("Disconnecting from FTP server");
            client.disconnect();
            showServerReply(client);
        } catch (Exception e) {
            tracer.error("Could not logout or disconnect", e);
            return false;
        }
    }

    return true;
}

From source file:ddf.test.itests.catalog.TestFtp.java

private void ftpPut(FTPClient client, String data, String fileTitle) throws IOException {
    LOGGER.info("Start data upload via FTP PUT...");

    boolean done;

    try (InputStream ios = new ByteArrayInputStream(data.getBytes())) {
        // file will not actually be written to disk on ftp server
        done = client.storeFile(fileTitle, ios);
    }//from   w ww . j a va  2  s .co  m

    showServerReply(client);

    if (done) {
        LOGGER.debug("File uploaded successfully.");
    } else {
        LOGGER.error("Failed to upload file.");
    }
}