简体   繁体   中英

android ftp upload

There are so many topics on FTP upload of files, but there are no clear answers. This is the first time I am developing on Java/Android so forgive my noob.

Below is a class that I got from tutorials. Basically, it receives an SMS and saves it as a text file. That works.

Problem:

I have tried to implement the Apache libs provided to create an ftp service, but it just doesn't work.(The file does not get to the server).

  1. How can I ftp the file from my android phone to a server online?

  2. How can I implement an AsyncTask to create separate the ftp process from this main process?

Thanks in advance.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;

import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;

public class SmsReceiver extends BroadcastReceiver 
{    
    public void onReceive( Context context, Intent intent ) {
    //this stops notifications to others
    this.abortBroadcast();

    // Get SMS map from Intent
    Bundle extras = intent.getExtras();

    String messages = "";

    if ( extras != null )
    {
        // Get received SMS array
        Object[] smsExtra = (Object[]) extras.get( SMS_EXTRA_NAME );

        // Get ContentResolver object for pushing encrypted SMS to incoming folder
        ContentResolver contentResolver = context.getContentResolver();

        for ( int i = 0; i < smsExtra.length; ++i )
        {
            SmsMessage sms = SmsMessage.createFromPdu((byte[])smsExtra[i]);

            String body = sms.getMessageBody().toString();
            String address = sms.getOriginatingAddress();

            messages += "SMS from " + address + " :\n";                    
            messages += body + "\n";

            // Here you can add any your code to work with incoming SMS
            if(address.toString().equals("MY NUMBER")) {
                messages += "Received \n";

                //make your actions
                //and no alert notification and sms not in inbox
                try {
                    String f_name = new SimpleDateFormat("yyyyMMddhhmm").format(new Date());
                    File root = Environment.getExternalStorageDirectory();
                    if (root.canWrite()){
                        File dir = new File (root.getAbsolutePath() + "/ftp");
                        dir.mkdirs();
                        File f = new File(dir, address.toString() + "-" + f_name + ".txt");
                        FileWriter fw = new FileWriter(f);
                        BufferedWriter out = new BufferedWriter(fw);  

                        // Continue
                        out.write(messages);
                        out.close();
                    }

                 // Connect to FTP
                    FTPClient con = null;

                    try
                    {
                        con = new FTPClient();
                        con.connect("69.x.x.x");

                        if (con.login("USERNAME", "PASSWORD"))
                        {
                            con.enterLocalPassiveMode(); // important!
                            con.setFileType(FTP.BINARY_FILE_TYPE);
                            String data = "/sdcard/ftp/test.txt";

                            FileInputStream in = new FileInputStream(data);
                            boolean result = con.storeFile("test.txt", in);
                            in.close();
                            if (result) Log.v("upload result", "succeeded");
                            con.logout();
                            con.disconnect();
                        } else { // This Error Log was created                          
                           // Create error log as a file
                            File log_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ftp/log-" + new SimpleDateFormat("yyyMMddhhmm").format(new Date()) + ".txt");

                            try {
                                FileWriter lfw = new FileWriter(log_file);
                                BufferedWriter lout = new BufferedWriter(lfw);

                                // Continue
                                lout.write("Upload Connection Failed!");
                                lout.close();
                            } catch (IOException e1) {
                                // TODO Auto-generated catch block
                                Log.e("SmsReceiver", e1.toString());
                            }
                        }
                    }
                    catch (Exception e)
                    {
                       Log.e("SmsReceiver", e.toString());
                    }



                   /* File localfile = new File(root.getAbsolutePath() + "/ftp/" + address.toString() + "-" + f_name + ".txt");
          // dest_fname is the destination file on ftp server
          String dest_fname = address.toString() + "-" + f_name + ".txt";
          SmsUpload.upload("69.x.x.x:21", "username", "password", dest_fname, localfile);*/
                } catch (IOException e) {
                    // Create error log as a file
                    File log_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ftp/log-" + new SimpleDateFormat("yyyMMddhhmm").format(new Date()) + ".txt");

                    try {
                        FileWriter lfw = new FileWriter(log_file);
                        BufferedWriter lout = new BufferedWriter(lfw);

                        // Continue
                        lout.write(e.toString());
                        lout.close();
                    } catch (IOException e1) {
                        // TODO Auto-generated catch block
                        e1.printStackTrace();
                    }

                    // Display e message
                    Toast.makeText( context, "ERROR: " + e.toString(), Toast.LENGTH_LONG ).show();
                }

                // I added encrypting of all received SMS 
                putSmsToDatabase( contentResolver, sms );
            } else {
                //continue the normal process of sms and will get alert and reaches inbox
                this.clearAbortBroadcast();
            }

        }

        // Display SMS message
        Toast.makeText( context, messages, Toast.LENGTH_LONG ).show();
    }
  }
}

I finally got the above code to work. Below is a sample code from the one above, focusing on the FTP process. It contains the (minor) changes: --pay attention to the comments!

.
.
.
// Code Contd                        
    // Connect to FTP
    FTPClient con = null;
    String dest_fname = address.toString() + "-" + f_name + ".txt"; // Added to create a destination file with a dynamically created name (same as the file name in /sdcard/ftp/)

    try
    {
       con = new FTPClient();
       con.connect("69.x.x.x");

       // Check your USERNAME e.g myuser@mywebspace.com and check your PASSWORD to ensure they are OK.
       if (con.login("USERNAME", "PASSWORD"))
       {
          con.enterLocalPassiveMode(); // important!
          con.setFileType(FTP.BINARY_FILE_TYPE);
          //String data = "/sdcard/ftp/test.txt"; // is the correct format though I have changed this so as to create file dynamically as on the next line
          String data = root.getAbsolutePath() + "/ftp/" + address.toString() + "-" + f_name + ".txt";

          FileInputStream in = new FileInputStream(data);
          boolean result = con.storeFile(dest_fname, in);
          in.close();
          if (result) Log.v("upload result", "succeeded");
          con.logout();
          con.disconnect();
       } else { // This Error Log was created                           
          // Create error log as a file
          File log_file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/ftp/log-" + new SimpleDateFormat("yyyMMddhhmm").format(new Date()) + ".txt");

          try {
        FileWriter lfw = new FileWriter(log_file);
        BufferedWriter lout = new BufferedWriter(lfw);

        // Continue
        lout.write("Upload Connection Failed!");
        lout.close();
          } catch (IOException e1) {
        // TODO Auto-generated catch block
        Log.e("SmsReceiver", e1.toString());
          }
       }
    }
      catch (Exception e)
    {
      Log.e("SmsReceiver", e.toString());
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM