views:

194

answers:

1

I'm writing an image file uploader for android for my favorite image gallery software and it uses FTP. I've started using Apache-Commons Net FTP as my ftp library based on past stack overflow questions. Like so:

FTPClient ftp = new FTPClient();
try{
  ftp.connect(host);
  Log.i(TAG,"we connected");
  if(!ftp.login(user,pass)){
    ftp.logout();
    //TODO: alert user it didn't happen
    return;
  }    
  String replyStatus = ftp.getStatus();
  Log.i(TAG,replyStatus);
  int replyCode = ftp.getReplyCode();
  if (!FTPReply.isPositiveCompletion(replyCode))
  {    
    ftp.disconnect();
    //TODO: alert user it didn't happen
    return;
  }    
  Log.i(TAG,"we logged in");
  ftp.changeWorkingDirectory(path);
  ftp.setFileType(ftp.BINARY_FILE_TYPE);
  for(int i = 0; i < contentUris.size(); i++){
    Log.i(TAG,"uploading new file");
    Uri stream = (Uri) contentUris.get(i);
    //InputStream in = openFileInput(getRealPathFromURI(stream));
    InputStream in =this.getContentResolver().openInputStream(stream);
    BufferedInputStream buffIn=null;
    buffIn=new BufferedInputStream(in);

    ftp.setFileType(ftp.BINARY_FILE_TYPE);
    boolean Store = ftp.storeFile("test.jpg", buffIn);
    Log.i(TAG, "uploaded test");
  }      
  ftp.disconnect();
}      
catch(Exception ex){
  //do something wise and smart and useful
}

I see in the log that I'm getting logged in, I'm able to change directories, and when I upload I get a test.jpg in my directory, but with 0 bytes size.

What gives? Am I not opening the input stream right? How do I properly do it?

If I'm not giving enough detail, let me know - the full code is also available on github

A: 

Looks like the problem is that you can't make an active ftp connection, you must use passive mode. So change the top to this: ftpClient.enterLocalPassiveMode();

FTPClient ftp = new FTPClient();
try{
  ftp.connect(host);
  ftp.enterLocalPassiveMode();
  Log.i(TAG,"we connected");
  if(!ftp.login(user,pass)){
    ftp.logout();
    //TODO: alert user it didn't happen
    return;
  }
  String replyStatus = ftp.getStatus();
  Log.i(TAG,replyStatus);
  int replyCode = ftp.getReplyCode();
  if (!FTPReply.isPositiveCompletion(replyCode))
  {
    ftp.disconnect();
    //TODO: alert user it didn't happen
    return;
  }

  Log.i(TAG,"we logged in");
  ftp.changeWorkingDirectory(path);
  ftp.setFileType(ftp.BINARY_FILE_TYPE);
  for(int i = 0; i < contentUris.size(); i++){
    Log.i(TAG,"uploading new file");
    Uri stream = (Uri) contentUris.get(i);
    String filePath = getRealPathFromURI(stream);
    InputStream in = new FileInputStream(filePath);
    ftp.setFileType(ftp.BINARY_FILE_TYPE);

    boolean Store = ftp.storeFile("test.jpg", in);
    Log.i(TAG, "uploaded test");
  }


  ftp.disconnect();
}
catch(Exception ex){
  //TODO: properly handle exception
  //Log.i(TAG,ex);
  //TODO:Alert the user this failed
}
MattK