首页 > 代码库 > Java之基于Apache jar包的FTPClient上传

Java之基于Apache jar包的FTPClient上传

  首先,准备工作:

http://pan.baidu.com/s/1dD1Utwt

从以上链接下载Apache的jar包,并将其复制到工程的WEB-INF下的lib包里,在此,准备工作就已经完成了。

  具体java代码实现

 1 FTPClient ftpClient = new FTPClient(); 2               try { 3                    4                    5                 ftpClient.connect("ftp服务器IP");
           //ftp服务器的用户名及密码,此处匿名用户,密码为空 
6 boolean b = ftpClient.login("anonymous", ""); 7 int reply = ftpClient.getReplyCode(); 8 if (!FTPReply.isPositiveCompletion(reply)) { 9 ftpClient.disconnect();10 System.err.println("FTP server refused connection!");11 System.exit(1);12 }13 14 ftpClient.setControlEncoding("UTF-8"); 15 FileInputStream fis = null;
              //此处为从jsp页面接受的文件
16 fis = new FileInputStream(file);
               //存储位置的dir
17 String remoteDir = "/uploads/"; 18 // set upload dir 19 ftpClient.changeWorkingDirectory(remoteDir); 20 ftpClient.setBufferSize(1024); 21 ftpClient.setControlEncoding("UTF-8"); 22 23 // set file type 24 ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE); 25 // upload               
//fileFileName也是jsp页面获取的26 b = ftpClient.storeFile(fileFileName, fis); 27 IOUtils.closeQuietly(fis); 28 ftpClient.logout(); 29 30 }catch (SocketException e) { 31 e.printStackTrace(); 32 } catch (IOException e) { 33 e.printStackTrace(); 34 }finally{ 35 ftpClient.disconnect();36 } 37

 

  至此结束

  有关FTP搭建可以看我的另一篇博客:http://www.cnblogs.com/voidy/p/3946243.html

 

Java之基于Apache jar包的FTPClient上传