FTP 上传:
需要通过判断当前要上传的文件是否是文件夹或者单独一个文件,单独文件直接通过
ftpClient.changeWorkingDirectory(remoteDir) 再
ftpClient.storeFile(uploadFile.getName(), uploadStream)即可
如果是文件夹 需要递归上传
代码如下
//上传文件夹
public boolean uploadDirectory(String localDirectory, String remoteDirectoryPath, String defaultRemotePath) {
File uploadFile = new File(localDirectory);
if (ftpClient == null || !ftpClient.isConnected()) {
logger.info("ftpClient service not ready.");
return false;
}
if (!uploadFile.isDirectory()){
//如果是文件可直接上传
uploadFile(remoteDirectoryPath,uploadFile,remoteDirectoryPath);
}
File[] allFile = uploadFile.listFiles();
try {
if (allFile != null) {
for (int i = 0; i < allFile.length; i++) {
File currentFile = allFile[i];
if (dateFileSuffix == null) {
dateFileSuffix = uploadFile.getName();
remoteDirectoryPath = remoteDirectoryPath.endsWith("/") ? remoteDirectoryPath +
dateFileSuffix : remoteDirectoryPath +"/" +dateFileSuffix;
}
String filePath = remoteDirectoryPath + "/" + currentFile.getName();
if (currentFile.isDirectory()) {
// 递归
uploadDirectory(currentFile.getPath(),
filePath, defaultRemotePath);
} else {
String uploadPath = filePath.substring(0, filePath.lastIndexOf("/"));
uploadFile(defaultRemotePath, currentFile, uploadPath);
}
}
}
} catch (Exception e) {
logger.error("uploadDirectory error", e);
}
return true;
}
//单独文件上传
//上传单个文件 public boolean uploadFile(String defaultRemotePath, File uploadFile, String remoteFtpPath) { boolean success = false; try { success = put(remoteFtpPath, uploadFile); } catch (Exception e) { logger.error("ftp upload file error.", e); } return success; }
//当前目录不存在逐级创建目录 public boolean put(String remotePathDir, File uploadFile) { boolean isMakeSucess = false; remotePathDir = remotePathDir.endsWith("/") ? remotePathDir :remotePathDir+"/"; try { if (!ftpClient.changeWorkingDirectory(remotePathDir)) { // 如果远程目录不存在,则递归创建远程服务器目录 int start = 0; int end = 0; if (remotePathDir.startsWith("/")) { start = 1; } end = remotePathDir.indexOf("/", start); while (true) { String subDirectory = remotePathDir.substring(start, end); if (!ftpClient.changeWorkingDirectory(subDirectory)) { if (ftpClient.makeDirectory(subDirectory)) { ftpClient.changeWorkingDirectory(subDirectory); } else { System.out.println("创建目录失败"); } } else { ftpClient.changeWorkingDirectory(subDirectory); } start = end + 1; end = remotePathDir.indexOf("/", start); // 检查所有目录是否创建完毕 if (end < start) { break; } } } BufferedInputStream uploadStream = new BufferedInputStream(new FileInputStream(uploadFile)); logger.info(uploadFile.getName() + "文件夹开始上传....."); isMakeSucess = ftpClient.storeFile(uploadFile.getName(), uploadStream); //上传成功后如果后续休要上传需要重新切换成根目录否则会在此目录继续创建文件夹 ftpClient.changeWorkingDirectory("/"); } catch (Exception e) { logger.error("makeDir error", e); } return isMakeSucess; }
最后还是要断开连接的哦
public void ftpDisconnect() { if (ftpClient != null || ftpClient.isConnected()) { try { ftpClient.disconnect(); } catch (Exception e) { logger.error("ftp client disconnect fail.", e); } } }