Reputation: 139
I am encoding my file into a base64 string. I want to transfer this to a sftp folder using JSch without creating a local file. How can I do that?
Upvotes: 0
Views: 1922
Reputation: 139
I Used put(String src, String dst)
method in ChannelSftp class
private void getConnection(String username, String hostname, String password) {
JSch jsch = new JSch();
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
try {
session = jsch.getSession(username, hostname, 22);
session.setConfig(config);
session.setPassword(password);
session.connect();
channel = session.openChannel(CHANNEL_TYPE);
channel.connect();
} catch (JSchException e) {
e.printStackTrace();
}
}
private void disconnectConnections() {
if (channel.isConnected()) {
channel.disconnect();
}
if (session.isConnected()) {
session.disconnect();
}
}
private String getConfiguration(String key) {
return configuration.getString(key);
}
public void uploadToSftp(String sftpFileLocation, String fileToBeUploaded, String filename) {
if (session == null || channel == null || !session.isConnected() || !channel.isConnected()) {
getConnection(getConfiguration(USERNAME), getConfiguration(HOST), getConfiguration(PASSWORD));
}
try {
channelSftp = (ChannelSftp) channel;
channelSftp.cd(sftpFileLocation);
byte[] data = BaseEncoding.base64().decode(fileToBeUploaded);
InputStream is = new ByteArrayInputStream(data);
channelSftp.put(is, filename);
disconnectConnections();
} catch (SftpException e) {
e.printStackTrace();
}
}
Upvotes: 0
Reputation: 821
You would probably use the method
void put(InputStream src, String dst, SftpProgressMonitor monitor, int mode)
in class ChannelSftp. JSch also provides an example on how to set up and tear down an SFTP session.
Upvotes: 1