首页 > 解决方案 > 用Java将字节数组上传到FTP

问题描述

我的目标是能够将文件上传到 FTP 服务器,我进行了一些研究,并看到了如果文件已经存储在本地,如何上传文件的方法,我有一个返回的函数,byte[]所以我想知道如何发送该文件如果文件存在于内存中,则发送到 FTP 服务器。

private void connect() throws IOException {
    FTPClient ftpClient = new FTPClient();
    ftpClient.addProtocolCommandListener(new PrintCommandListener(new PrintWriter(System.out)));
    ftpClient.connect(ftp.getServer(), ftp.getPort());
    int reply = ftpClient.getReplyCode();
    if (!FTPReply.isPositiveCompletion(reply)) {
        ftpClient.disconnect();
        throw new RuntimeException("Could not connect to FTP Server");
    } else {
        ftpClient.login(ftp.getUser(), ftp.getPassword());
    }
}

标签: javaftpuploadapache-commons-net

解决方案


您似乎正在使用 Apache Commons Net FTPClient

它实际上甚至没有直接上传物理文件的方法。它的FTPClient.storeFile方法只接受InputStream接口。

通常您会使用FileInputStream来指代物理文件:
如何将文件上传到 FTP 服务器?

当您想使用时ByteArrayInputStream
我们可以将字节数组转换为 Java 中的 InputStream 吗?

InputStream inputStream = new ByteArrayInputStream(bytes);
ftpClient.storeFile(remotePath, inputStream);

推荐阅读