FTP文件上传不报错但是未成功上传
使用FTPClient进行文件上传,网上找的案例发现在服务器上上传后ftp中并没有文件.
解决
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
原因分析
完整代码
/**
* <pre>
*
* <dependency>
<groupId>commons-net</groupId>
<artifactId>commons-net</artifactId>
<version>3.6</version>
</dependency>
*
* </pre>
*
* @author eoekun
* @createTime 2018年4月20日 下午3:05:21
*/
public class FTPUtil {
/**
* Description: 向FTP服务器上传文件 @Version1.0 Jul 27, 2008 4:31:09 PM by
* 崔红保(cuihongbao@d-heaven.com)创建
*
* @param url
* FTP服务器hostname
* @param port
* FTP服务器端口
* @param username
* FTP登录账号
* @param password
* FTP登录密码
* @param path
* FTP服务器保存目录
* @param filename
* 上传到FTP服务器上的文件名
* @param input
* 输入流
* @return 成功返回true,否则返回false
*/
public static boolean uploadFile(String url, int port, String username, String password, String path, String filename,
InputStream input) {
boolean success = false;
FTPClient ftp = new FTPClient();
try {
int reply;
ftp.connect(url, port);
ftp.login(username, password);
reply = ftp.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply)) {
ftp.disconnect();
return success;
}
ftp.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftp.enterLocalPassiveMode();
ftp.changeWorkingDirectory(path);
ftp.storeFile(filename, input);
input.close();
ftp.logout();
success = true;
} catch (IOException e) {
e.printStackTrace();
} finally {
if (ftp.isConnected()) {
try {
ftp.disconnect();
} catch (IOException ioe) {
}
}
}
return success;
}
private String url = "ftp.eoekun.top";
private int port = 21;
private String userName = "test";
private String password = "test";
@Test
public void testUpLoadFromDisk() {
try {
FileInputStream in = new FileInputStream(new File("/Users/eoekun/Desktop/test.txt"));
boolean flag = uploadFile(url, port, userName, password, "/test-eoekun/", "/test-eoekun/test.txt", in);
System.out.println(flag);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}