21xrx.com
2024-09-08 11:30:37 Sunday
登录
文章检索 我的文章 写文章
我最近在做一个Java应用程序
2023-06-10 15:31:36 深夜i     --     --
Java 上传文件 远程服务器

我最近在做一个Java应用程序,需要实现文件上传功能,上传到远程服务器上。我在网上查阅了一些资料,最终成功实现文件上传功能,并且在这里与大家分享一下。

实现上传的核心代码如下:


public static void uploadFile(String remoteIP, int port, String username, String password, String remotePath, String fileName, InputStream inputStream) {

  try {

    JSch ssh = new JSch();

    // 创建session并且打开连接,因为创建Session后要主动打开连接

    Session session = ssh.getSession(username, remoteIP, port);

    session.setPassword(password);

    // 设置ssh连接传输文件时不验证host key,这里设置成不验证,不建议在生产环境中使用

    session.setConfig("StrictHostKeyChecking", "no");

    session.connect(30000);

    // 打开sftp通道

    ChannelSftp sftp = (ChannelSftp) session.openChannel("sftp");

    sftp.connect(1000);

    // 判断远程路径是否存在,不存在则创建

    try {

      sftp.cd(remotePath);

    } catch (SftpException e) {

      sftp.mkdir(remotePath);

      sftp.cd(remotePath);

    }

    // 上传文件,文件名重名则覆盖

    sftp.put(inputStream, fileName, ChannelSftp.OVERWRITE);

    sftp.disconnect();

    session.disconnect();

  } catch (Exception e) {

    e.printStackTrace();

  }

}

第一个参数是远程服务器的IP地址,第二个参数是端口号,第三个参数是用户名,第四个参数是密码,第五个参数是远程文件路径,第六个参数是上传后的文件名,第七个参数是输入流。这个方法可以直接将输入流写入到远程服务器的指定路径下,如果需要在本地的文件上传到远程服务器,只需要将本地文件转换成输入流即可。

使用这个方法的代码如下:


String remoteIP = "192.168.xx.xx";

int port = 22;

String username = "root";

String password = "******";

String remotePath = "/data/upload/";

String fileName = "test.txt";

File file = new File("D:/test.txt");

InputStream inputStream = new FileInputStream(file);

uploadFile(remoteIP, port, username, password, remotePath, fileName, inputStream);

这里我以上传test.txt文件为例,在方法中将输入流写入到了/data/upload/文件夹下,并且重命名为test.txt。

通过这篇文章,我成功实现了文件上传到远程服务器的功能,并分享了具体的实现过程和核心代码,希望能够帮助到有需要的读者。

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章