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

时间:2016-10-06 12:45:50

标签: java excel ftp apache-commons-net

我是这类工作的新手所以请帮助我。 我将xlsx文件(excel文件)发送到服务器,我的代码中没有错误,并且在ftp服务器中,我在xampp中使用filezilla。我在谷歌搜索并说它必须存储在一个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) {
       }
   }

我的问题的任何解决方案?

2 个答案:

答案 0 :(得分:3)

您需要使用 -

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

另外,添加try并捕捉upload.storeFile以确保其存储文件。

答案 1 :(得分:-1)

尝试以下

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();
    }
}