Parth Patel Parth Patel - 1 year ago 126
Java Question

Save images to SFTP server using java

public static void main(String[] args) {
String SFTPHOST = "";
int SFTPPORT = 22;
String SFTPUSER = "username";
String SFTPPASS = "password";
String SFTPWORKINGDIR = "/export/home/kodehelp/";

Session session = null;
Channel channel = null;
ChannelSftp channelSftp = null;

JSch jsch = new JSch();
session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
java.util.Properties config = new java.util.Properties();
config.put("StrictHostKeyChecking", "no");
channel = session.openChannel("sftp");
channelSftp = (ChannelSftp)channel;;
URL url = new URL("");
BufferedImage image = null;
image =;

**File f = new File(FILETOTRANSFER);
channelSftp.put(new FileInputStream(f), f.getName());**
}catch(Exception ex){


I don't know, how to store image to SFTP server. I am confused about what to write instead of this two line

File f = new File(FILETOTRANSFER);

channelSftp.put(new FileInputStream(f), f.getName());

I am using JSCH library to connect with SFTP
Thanks in advance.

Answer Source

The problem is that you're loading the image into a BufferedImage, but that's not a representation you can directly write to an SFTP server.

It's much easier to directly open an InputStream on the URL and save that to the SFTP server. (Using url.openStream())

You then need to come up with a suitable file name - here I take the last part of the URL after the last slash, which has the same effect as what you did in your code.

URL url = new URL(
String path = url.getPath();
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download