---
title: "使用FTP做图片服务器出现的问题"
author: "showtime520"
date: "2008-12-24T10:31:26Z"
tags: []
slug: "ftp"
draft: false
lastmod: "2008-12-24T11:34:10Z"
id: 300278
url: "https://showtime520.iteye.com/blog/300278"
---

<span style="color:red">FTP上传文件长度为空的问题</span>
这个问题是没有调用FTPClient的ftp.completePendingCommand();
原来在一个文件传输过程中会产生两个Reply:
150 Opening BINARY mode data connection for 上传文件的名字
226 Transfer complete.
而FTPClient自动消费掉一个,于是解析Reply就发生了错位, 下一个命令的会解析266那条. 接下来的命令都不是解析自己的Reply而是前一次命令的. 所有在PASV命令的Reply码就不对了, FTPClient也就不会执行接下来本应该执行RETR命令.
所以有时候当FTP传输文件的时候是没问题的（一般是第一次），后面的就会发生错位了。故文件传输后为0.
而FTPClient的completePendingCommand()方法就是用来把前面传输完毕的Reply清空的。
（因为我是使用SPRING来管理FtpServer这个类的，是单例，所以有上面的问题，如果传输一次就NEW一下，估计没这个问题。）

伪代码如下

```java

try{
os=ftp.storeFileStream(File.separatorChar+folderName+fileName);
LogFactory.log("上传文件"+fileName+"至FTP服务器", Level.DEBUG, null);
if(os!=null){	
      int bytesRead = 0;
      byte[] buffer = new byte[1024];
      while((bytesRead=fileInputStream.read(buffer,0,1024))!=-1){
	  System.out.println("图片长度"+bytesRead);
	   os.write(buffer,0,bytesRead);
           
	   os.flush();
	}
     }
}catch(){

}finally{
   //先关文件上传流
   fileInputStream.close();
   //再关FTP输入流
   os.close();
   //一定要加，否则上传至FTP服务器的文件可能长度为0
   ftp.completePendingCommand();

}

```