現象:今天在用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("關閉服務器連接異常"); } } } }