环境是windows,服务器端使用apache-FtpServer,客户端使用apache-commons-net包中的FtpClient。
现在出现的问题如题,下面是一次上传后在服务器端产生的日志:
[ INFO] 2011-04-07 22:50:00,531 [] [127.0.0.1] CREATED
[ INFO] 2011-04-07 22:50:00,531 [] [127.0.0.1] OPENED
[ INFO] 2011-04-07 22:50:00,531 [] [127.0.0.1] SENT: 220 Service ready for new user.
[ INFO] 2011-04-07 22:50:00,531 [] [127.0.0.1] RECEIVED: USER admin
[ INFO] 2011-04-07 22:50:00,531 [admin] [127.0.0.1] SENT: 331 User name okay, need password for admin.
[ INFO] 2011-04-07 22:50:00,531 [admin] [127.0.0.1] RECEIVED: PASS *****
[ INFO] 2011-04-07 22:50:00,531 [admin] [127.0.0.1] Login success - admin
[ INFO] 2011-04-07 22:50:00,531 [admin] [127.0.0.1] SENT: 230 User logged in, proceed.
[ INFO] 2011-04-07 22:50:00,546 [admin] [127.0.0.1] RECEIVED: PORT 127,0,0,1,152,102
[ INFO] 2011-04-07 22:50:00,546 [admin] [127.0.0.1] SENT: 200 Command PORT okay.
[ INFO] 2011-04-07 22:50:00,546 [admin] [127.0.0.1] RECEIVED: STOR ??.txt
[ INFO] 2011-04-07 22:50:00,546 [admin] [127.0.0.1] SENT: 150 File status okay; about to open data connection.
[ INFO] 2011-04-07 22:50:00,546 [admin] [127.0.0.1] SENT: 551 /??.txt: Error on output file.
[ INFO] 2011-04-07 22:50:00,546 [admin] [127.0.0.1] RECEIVED: QUIT
[ INFO] 2011-04-07 22:50:00,546 [admin] [127.0.0.1] CLOSED
日志中“??.txt”便是要上传的中文文件名文件。感觉像是编码问题。但是google了一把,发现别人都是能上传,只是上传后的内容有乱码问题。尔我是压根就传不了。又尝试上传了一个英文名,内容中有中文的文件。上传后到服务器目录查看,一切都正常。怀疑会不会是服务器端的编码设置,但是也没找到相关的提问和解决方法。故发此贴向兄弟姐妹们求助!!!!
------解决方案--------------------------------------------------------
我的代码,希望对你有帮助............
- Java code
try { int reply; ftp.connect(ip, port); //下面三行代码必须要,而且不能改变编码格式,否则不能正确下载中文文件 ftp.setControlEncoding("GBK"); FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT); conf.setServerLanguageCode("zh"); //如果采用默认端口,可以使用ftp.connect(url) 的方式直接连接FTP服务器 ftp.login(username, password);//登录 reply = ftp.getReplyCode(); if (!FTPReply.isPositiveCompletion(reply)) { ftp.disconnect(); return success; } //ftp.changeWorkingDirectory(remotePath);//转移到FTP服务器目录 chgDir=ftp.changeWorkingDirectory(new String(remotePath.getBytes(),"ISO-8859-1")); if (chgDir) { FTPFile[] fs = ftp.listFiles(); for (int i = 0; i < fs.length; i++) { FTPFile ff = fs[i]; if (ff.getName().equals(fileName)) { File localFile = new File(localPath + File.separator + ff.getName()); OutputStream is = new FileOutputStream(localFile); //注意此处retrieveFile的第一个参数由GBK转为ISO-8859-1编码。否则下载后的文件内容为空。 //原因可能是由于aix系统默认的编码为ISO-8859-1 ftp.retrieveFile(new String(ff.getName().getBytes("GBK"), "ISO-8859-1"), is); is.close(); } } } ftp.logout(); success = true; } catch (IOException e) { e.printStackTrace(); } finally { if (ftp.isConnected()) { try { ftp.disconnect(); } catch (IOException ioe) { } } }
------解决方案--------------------------------------------------------
1.首先apache-FtpServer 默认使用的是utf-8, 查看FtpServerProtocolCodecFactory源码可知 可知它的encode,decode 都是使用的是utf-8.
2.ftp命令走的是control connection, 所以客户端要使用 ftpClient.setControlEncoding("UTF-8");