个性化阅读
专注于IT技术分析

如何在Android中使用JSCH(SFTP)将文件上传到服务器

点击下载

使用JSCH库, 使用Java创建sftp客户端变得非常容易。

JSch是SSH2的纯Java实现(我们可以使用SFTP Channel)。 JSch允许你连接到sshd服务器并使用端口转发, X11转发, 文件传输等, 并且可以将其功能集成到你自己的Java程序中。 JSch已获得BSD样式许可。

你可以使用以下代码使用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();
}

该函数将使用put方法为你解决问题。你只需要拥有文件的路径并为该文件提供新的远程路径

请记住, 作为示例, 这不包括任何安全性。如果服务器使用已知主机文件, 则需要添加已知主机文件;如果服务器使用私钥进行身份验证, 则需要添加标识。

如果你需要显示上传进度, 请阅读本文并学习如何做。

此代码可在使用Java和JSCH库的任何平台(Android, 桌面等)上运行。

赞(0)
未经允许不得转载:srcmini » 如何在Android中使用JSCH(SFTP)将文件上传到服务器

评论 抢沙发

评论前必须登录!