上传目录到 FTP ( Android )

Upload directory to FTP ( Android )

我想将目录上传到我的 FTP 服务器。

这是我用来上传"single file"到我的ftp服务器的代码,我想知道是否有什么东西可以帮助我上传所有图片“.jpg”在这个文件夹 "mnt/sdcard/DCIM/Camera" 到我的 FTP.

public static final String TAG = "Contacts";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread t = new Thread(new Runnable(){
        @Override
        public void run(){
            jetzt();
        }
    });
    t.start();
    Log.i(TAG, "thread started");

}

public void jetzt(){
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect("HOST SERVER IP");

        ftpClient.setSoTimeout(10000);
        ftpClient.enterLocalPassiveMode();
        if(ftpClient.login(" LOGIN ", " PASSWORD "))
        {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
            File sFile=new File("mnt/sdcard/DCIM/Camera/mypicture.jpg");
            FileInputStream fs= new FileInputStream(sFile);
            String fileName = sFile.getName();
            Boolean result = ftpClient.storeFile(fileName, fs);
            fs.close();
            Log.i(TAG, "sent");
            String has = "";
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

FTPClient class.

中没有上传整个目录的功能

你必须:

  • 枚举目录中的所有文件。
    参见 How to read all files in a folder from Java? or even Recursively list files and directories in an FTP server using Java.

  • 一一上传。

您可以使用这个修改后的函数:

public void jetzt() {
    FTPClient ftpClient = new FTPClient();
    try {
        ftpClient.connect("HOST SERVER IP");

        ftpClient.setSoTimeout(10000);
        ftpClient.enterLocalPassiveMode();
        if (ftpClient.login(" LOGIN ", " PASSWORD ")) {
            ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
            ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);

            final File folder = new File("mnt/sdcard/DCIM/Camera");

            for (final File fileEntry : folder.listFiles()) {
                try {
                    FileInputStream fs = new FileInputStream(fileEntry);
                    if (!fileEntry.isDirectory()) {
                        String fileName = fileEntry.getName();
                        ftpClient.storeFile(fileName, fs);
                        fs.close();
                        Log.i(TAG, "sent");
                    }
                } catch (Exception e) {
                    Log.i(TAG, "error uploading");
                }
            }
        }
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}