org.apache.commons.net.ftp.FTPClient上傳文件大小改變的解決方法


 

現象:今天在用org.apache.commons.net.ftp.FTPClient的storeFile方法時,發現上傳小文件如幾KB的情況下,文件是無損傳輸,但是當上傳的文件是55M以及100多兆的時候,FTP上的服務器文件的大小就會增加。

解決方法:在連接FTP服務器的時候,加上一段這個代碼ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);

 

示例:

連接FTP服務器代碼:

public static FTPClient getFtpClient(String serverIP,String userName,String password,int port) throws SocketException, IOException{
         int reply;
             FTPClient ftpClient = new FTPClient();
             ftpClient.connect(serverIP, port);
             reply = ftpClient.getReplyCode();
            
            if(!FTPReply.isPositiveCompletion(reply)){
                ftpClient.disconnect();
                System.out.println("登陸FTP失敗");
                return null;
            }
            ftpClient.login(userName, password);
            ftpClient.setDataTimeout(2000);
            ftpClient.enterLocalPassiveMode();
            ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); return ftpClient;
    }

上傳文件方法的代碼:

/**
     * 上傳文件到文件服務器中
     * @param file  需上傳的文件
     * @param ftpClient  
     * @param workDirectory   FTP服務器的相對目錄
     * @return
     * @throws IOException
     */
    public static String uploadFileToBBK(File file,FTPClient ftpClient,String workDirectory) throws IOException{
        
        ftpClient.setControlEncoding("UTF-8");
        ftpClient.makeDirectory(workDirectory);
        ftpClient.changeWorkingDirectory(workDirectory);
        BufferedInputStream  fiStream =new BufferedInputStream(new FileInputStream(file));
        boolean  flag = ftpClient.storeFile(new String((file.getName()).getBytes("UTF-8"),"iso-8859-1"),fiStream);
        fiStream.close();
        if(flag){
            return "OK";
        }else{
            return "";
        }
    }

斷開服務器連接方法的代碼:

public static void closeFtp(FTPClient ftpClient){
        if(ftpClient!=null && ftpClient.isConnected()){
            try {
                boolean isLogOut = ftpClient.logout();
                if(isLogOut){
                    System.out.println("成功關閉ftp連接");
                }
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
                System.out.println("關閉FTP服務器異常");
            }finally{
                try {
                    ftpClient.disconnect();
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    System.out.println("關閉服務器連接異常");
                }
            }
            
        }
    }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM