How to upload a file to a server using JSCH (SFTP) in android

How to upload a file to a server using JSCH (SFTP) in android

Create a sftp client with Java has become really easy using JSCH Library.

JSch is a pure Java implementation of SSH2 (We can use SFTP Channel). JSch allows you to connect to an sshd server and use port forwarding, X11 forwarding, file transfer, etc., and you can integrate its functionality into your own Java programs. JSch is licensed under BSD style license.

You can use the following code to upload a file to a remote path from a device with java : 

// Remember use the required imports (the library as well) using :

import com.jcraft.jsch.*;

/// then in our function

try {
     JSch ssh = new JSch();
     Session session = ssh.getSession("username", "myip90000.ordomain.com", 22);
     // Remember that this is just for testing and we need a quick access, you can add an identity and known_hosts file to prevent
     // Man In the Middle attacks
     java.util.Properties config = new java.util.Properties();
     config.put("StrictHostKeyChecking", "no");
     session.setConfig(config);
     session.setPassword("Passw0rd");
     
     session.connect();
     Channel channel = session.openChannel("sftp");
     channel.connect();

     ChannelSftp sftp = (ChannelSftp) channel;

     sftp.cd(directory);
     // If you need to display the progress of the upload, read how to do it in the end of the article

     // use the put method , if you are using android remember to remove "file://" and use only the relative path
     sftp.put("/storage/0/myfile.txt", "/var/www/remote/myfile.txt");

     Boolean success = true;

     if(success){
       // The file has been uploaded succesfully
     }
 
     channel.disconnect();
     session.disconnect();
} catch (JSchException e) {
    System.out.println(e.getMessage().toString());
    e.printStackTrace();  
} catch (SftpException e) {
    System.out.println(e.getMessage().toString());
    e.printStackTrace();
}


This function will do the trick for you, it uses the put method. You only need to have the path of the file and give a new remote path to the file

Remember that as an example, this doesn't include any security. You need to add the known hosts files if your server uses one, or add an identity if your server uses a Private key for authentication.

If you need to show an upload progress read this article and learn how to do it.

This code works on any platform that uses Java and JSCH Library (Android, desktop etc).

Become a more social person