Wednesday, May 25, 2016

SFTP file upload android example


Uploading files from Android using SFTP.

Jars files Needed

1) commons-logging-1.2.jar
2) commons-vfs2-2.1.jar
3) jsch-0.1.53.jar

Make sure you call this in a background thread.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
package com.adroitapps.ttcl.utils;

import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;

import java.io.File;

/**
* Created by pratap.kesaboyina on 24-05-2016.
*/
public class SftpClass {


public static void uploadFile(File file) {


String host = "", username = "",
password = "";


String localFilePath = file.getAbsolutePath();

String fileName = localFilePath.substring(localFilePath.lastIndexOf("/") + 1);

String remoteFilePath = "/foldername/" + fileName;


JSch jsch = new JSch();
Session session = null;
try {
session = jsch.getSession(username, host, 22);
session.setConfig("StrictHostKeyChecking", "no");
session.setPassword(password);
session.connect();

Channel channel = session.openChannel("sftp");
channel.connect();
ChannelSftp sftpChannel = (ChannelSftp) channel;
sftpChannel.put(localFilePath, remoteFilePath);
sftpChannel.exit();
session.disconnect();
} catch (JSchException e) {
e.printStackTrace();
} catch (SftpException e) {
e.printStackTrace();

}
}
}



Reference from stackoverflowlink





No comments:

Post a Comment