依赖:
2.代码如下: 其中PropertiesUtil类请参考另外一篇
importorg.apache.commons.net.ftp.FTPClient;
importorg.slf4j.Logger;
importorg.slf4j.LoggerFactory;
importjava.io.File;
importjava.io.FileInputStream;
importjava.io.IOException;
importjava.util.ArrayList;
importjava.util.List;
public class FTPUtil {
private static finalLogger logger = LoggerFactory.getLogger(FTPUtil.class);
private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
private static String ftpUser = PropertiesUtil.getProperty("ftp.user");
private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");
public FTPUtil(Stringip,intport,Stringuser,Stringpwd){
this.ip = ip;
this.port = port;this.user = user;
this.pwd = pwd;
}
public static boolean uploadFile(List fileList)throwsIOException {
FTPUtil ftpUtil =new FTPUtil(ftpIp,21,ftpUser,ftpPass);
logger.info("开始连接ftp服务器");
boolean result = ftpUtil.uploadFile("img",fileList);
logger.info("开始连接ftp服务器,结束上传,上传结果:{}");
return result;
}
private boolean uploadFile(StringremotePath,List fileList)throwsIOException {
booleanuploaded =true;
FileInputStream fis =null;
//连接FTP服务器
if(connectServer(this.ip,this.port,this.user,this.pwd)){
try{
ftpClient.changeWorkingDirectory(remotePath);
ftpClient.setBufferSize(1024);
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
ftpClient.enterLocalPassiveMode();
for(File fileItem : fileList){
fis =newFileInputStream(fileItem);
ftpClient.storeFile(fileItem.getName(),fis);
}
}catch(IOException e) {
logger.error("上传文件异常",e);
uploaded =false;
e.printStackTrace();
}finally{
fis.close();
ftpClient.disconnect();
}
}
return uploaded;
}
private boolean connectServer(Stringip,intport,Stringuser,Stringpwd){
booleanisSuccess =false;
ftpClient =newFTPClient();
try{
ftpClient.connect(ip);
isSuccess = ftpClient.login(user,pwd);
}catch(IOException e) {
logger.error("连接FTP服务器异常",e);
}
return isSuccess;
}
public static void main(String[] args)throwsIOException {
List files =newArrayList<>();
files.add(newFile("C:\\Users\\sifu\\Desktop\\DFSLIJ.html"));
if(uploadFile(files)){
System.out.println("成功");
}
}
private String ip;
private intport ;
private String user;
private String pwd;
private FTPClient ftpClient;
public String getIp() {
returnip;
}
public void setIp(Stringip) {this.ip = ip; }
public intget Port() {returnport; }
public void setPort(intport) {this.port = port; }
public String getUser() {returnuser; }
public void setUser(Stringuser) {this.user = user; }
public String getPwd() {returnpwd; }
public void setPwd(Stringpwd) {this.pwd = pwd; }
public FTPClient getFtpClient() {returnftpClient; }
public void setFtpClient(FTPClient ftpClient) {this.ftpClient = ftpClient; }}
####指导qq:179061434
####求求你尽情蹂躏我吧:
![image.png](https://img.haomeiwen.com/i5949949/604671c69b8a85e6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
网友评论