java ftp 传输文件导致文件损坏

java ftp transferring file resulting in corrupted file

我刚接触这种工作,所以请帮助我。 我向服务器发送了一个 xlsx 文件(一个 excel 文件),我的代码没有错误,在 ftp 服务器中,我在 xampp 中使用了 filezilla。我在 google 中搜索并说它必须存储在 zip 文件中,但 zip 文件也已损坏。 这是我的代码

 FTPClient upload= new FTPClient();
   File firstLocalFile = new File("C:/Users/user/desktop/sample.xlsx");
   InputStream inputStream = new FileInputStream(firstLocalFile);
   try {

       upload.connect("localhost");
       upload.login("user", "pass");
       upload.enterLocalPassiveMode();
       upload.storeFile("sample.zip", inputStream);
   } finally {
       try {
           upload.logout();
           upload.disconnect();
       } catch (Exception e) {
       }
   }

我的问题有什么解决方案吗?

您需要使用 -

设置文件类型
upload.setFileType(FTPClient.BINARY_FILE_TYPE);

此外,在 upload.storeFile 周围添加 try 和 catch 以确保其存储文件。

尝试以下方法

public void fetchFile() throws Exception {
    final FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect(this.serverDetails.getHostName(), this.serverDetails.getPort());
        if (!ftpClient.login(this.serverDetails.getUserName(), this.serverDetails.getPassword())) {
            throw new IOException("cannot login to server (server reply: " + ftpClient.getReplyCode());
        }
        if (!FTPReply.isPositiveCompletion(ftpClient.getReplyCode())) {
            throw new IOException("Exception in connecting to FTP Server");
        }
        final FTPFile ftpFile = ftpClient.mlistFile(this.serverDetails.getPath());
        if (ftpFile.isFile()) {
            final InputStream is = ftpClient.retrieveFileStream(this.serverDetails.getPath());
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.enterLocalPassiveMode();
            copyFromRemote(is, ftpFile.getSize());
        } else {
            throw new IOException("Remote file Doesnot Exist");
        }

    } catch (final Exception e) {
        throw e;
    }

    finally {
        ftpClient.logout();
        ftpClient.disconnect();
    }
}