这是我的代码:
public void UploadIt(){
org.apache.commons.net.ftp.FTPClient con = null;
try
{
con = new FTPClient();
con.connect("ftp server");
if (con.login("username", "pass"))
{
con.enterLocalPassiveMode(); // important!
con.setFileType(FTP.BINARY_FILE_TYPE);
String data = baseDir + "/emre";
FileInputStream in = new FileInputStream(new File(data));
boolean result = con.storeFile("/", in);
in.close();
if (result) Log.v("upload result", "succeeded");
con.logout();
con.disconnect();
}
}
catch (Exception e)
{
e.printStackTrace();
Log.v(" dead","ddsd");
}
}
我可以上传文件,但我无法上传目录。当我尝试上传目录或文件夹时,它会显示“...是目录”并且它不会上传。
答案 0 :(得分:1)
在ftp上创建目录后,你必须从目录中递归上传文件,因为在ftp上创建文件夹和文件创建不能同时完成它们是单独的命令。
public static void uploadDirectory(FTPClient ftpClient,
String remoteDirPath, String localParentDir, String remoteParentDir)
throws IOException {
System.out.println("LISTING directory: " + localParentDir);
File localDir = new File(localParentDir);
File[] subFiles = localDir.listFiles();
if (subFiles != null && subFiles.length > 0) {
for (File item : subFiles) {
String remoteFilePath = remoteDirPath + "/" + remoteParentDir
+ "/" + item.getName();
if (remoteParentDir.equals("")) {
remoteFilePath = remoteDirPath + "/" + item.getName();
}
if (item.isFile()) {
// upload the file
String localFilePath = item.getAbsolutePath();
System.out.println("About to upload the file: " + localFilePath);
boolean uploaded = uploadSingleFile(ftpClient,
localFilePath, remoteFilePath);
if (uploaded) {
System.out.println("UPLOADED a file to: "
+ remoteFilePath);
} else {
System.out.println("COULD NOT upload the file: "
+ localFilePath);
}
} else {
// create directory on the server
boolean created = ftpClient.makeDirectory(remoteFilePath);
if (created) {
System.out.println("CREATED the directory: "
+ remoteFilePath);
} else {
System.out.println("COULD NOT create the directory: "
+ remoteFilePath);
}
// upload the sub directory
String parent = remoteParentDir + "/" + item.getName();
if (remoteParentDir.equals("")) {
parent = item.getName();
}
localParentDir = item.getAbsolutePath();
uploadDirectory(ftpClient, remoteDirPath, localParentDir,
parent);
}
}
}
}
public static boolean uploadSingleFile(FTPClient ftpClient,
String localFilePath, String remoteFilePath) throws IOException {
File localFile = new File(localFilePath);
InputStream inputStream = new FileInputStream(localFile);
try {
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
return ftpClient.storeFile(remoteFilePath, inputStream);
} finally {
inputStream.close();
}
}
来源:http://www.codejava.net/java-se/networking/ftp/how-to-upload-a-directory-to-a-ftp-server