Parth Patel
Parth Patel

Reputation: 148

Save images to SFTP server using java

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

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

try{
            JSch jsch = new JSch();
            session = jsch.getSession(SFTPUSER,SFTPHOST,SFTPPORT);
            session.setPassword(SFTPPASS);
            java.util.Properties config = new java.util.Properties();
            config.put("StrictHostKeyChecking", "no");
            session.setConfig(config);
            session.connect();
            channel = session.openChannel("sftp");
            channel.connect();
            channelSftp = (ChannelSftp)channel;
            channelSftp.cd(SFTPWORKINGDIR);
            URL url = new URL("https://65.media.tumblr.com/839a07990f2b1ffa32065513c6224493/tumblr_oe6t3aYpHc1qfilt7o1_500.jpg");
            BufferedImage image = null;
            image = ImageIO.read(url);

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

}

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

Upvotes: 1

Views: 1226

Answers (1)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31299

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(
        "https://65.media.tumblr.com/839a07990f2b1ffa32065513c6224493/tumblr_oe6t3aYpHc1qfilt7o1_500.jpg");
String path = url.getPath();
channelSftp.put(url.openStream(),path.substring(path.lastIndexOf('/')+1));

Upvotes: 1

Related Questions