使用lib SimpleFTP将图像上传到Android中的FTP

时间:2016-05-08 15:21:27

标签: java android ftp

我想将文件上传到FTP。我使用的是simpleftp.jar。这是我的代码,它总是失败停止工作

MainActivity.java

import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import org.jibble.simpleftp.SimpleFTP;

import java.io.File;

import java.io.IOException;

public class MainActivity extends AppCompatActivity {
    private static int RESULT_LOAD_IMG = 1;
    String imgDecodableString;

    Button btn;

    TextView tv;
    static final String FTP_HOST= "ftp://ftp.lomapod.esy.es/";

    /*********  FTP USERNAME ***********/
    static final String FTP_USER = "xxxxxxxxxx";

    /*********  FTP PASSWORD ***********/
    static final String FTP_PASS  ="xxxxxxxxx";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btn=(Button) findViewById(R.id.buttonUploadPicture);
        tv=(TextView) findViewById(R.id.textView);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                File f = new File(imgDecodableString);
                String name=f.getName();

                // Upload sdcard file
                uploadFile(name);
            }
        });
    }

//    public void onClick(View v){
//
////        Bundle b=new Bundle();
////        Intent i=new Intent(getApplication(), DetailTransActivity.class);
////        Toast.makeText(this, "Upload Bukti Transaksi Berhasil",
////                Toast.LENGTH_LONG).show();
////        i.putExtras(b);
////        startActivity(i);
//
//    }

    public void loadImagefromGallery(View view) {
        // Create intent to Open Image applications like Gallery, Google Photos
        Intent galleryIntent = new Intent(Intent.ACTION_PICK,
                android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // Start the Intent
        startActivityForResult(galleryIntent, RESULT_LOAD_IMG);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        try {
            // When an Image is picked
            if (requestCode == RESULT_LOAD_IMG && resultCode == RESULT_OK
                    && null != data) {
                // Get the Image from data


                Uri selectedImage = data.getData();
                String[] filePathColumn = { MediaStore.Images.Media.DATA };

                // Get the cursor
                Cursor cursor = getContentResolver().query(selectedImage,
                        filePathColumn, null, null, null);
                // Move to first row
                cursor.moveToFirst();

                int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
                String filename = cursor.getString(columnIndex);
                imgDecodableString = cursor.getString(columnIndex);
                cursor.close();

                File f= new File(""+imgDecodableString);
                f.getName();
                ImageView imgView = (ImageView) findViewById(R.id.imgView);
                // Set the Image in ImageView after decoding the String
                imgView.setImageBitmap(BitmapFactory
                        .decodeFile(imgDecodableString));

            } else {
                Toast.makeText(this, "Pilih Bukti Transaksi",
                        Toast.LENGTH_LONG).show();
            }
        } catch (Exception e) {
            Toast.makeText(this, "Upload Bukti Transaksi Gagal", Toast.LENGTH_LONG)
                    .show();
        }
    }

    public void uploadFile(String fileName){


        try {
            SimpleFTP ftp = new SimpleFTP();

            // Connect to an FTP server on port 21.
            ftp.connect(FTP_HOST, 21, FTP_USER, FTP_PASS);

            // Set binary mode.
            ftp.bin();

            // Change to a new working directory on the FTP server.
            ftp.cwd("/assets/");

            // Upload some files.
            ftp.stor(new File(fileName));


            // Quit from the FTP server.
            ftp.disconnect();
            Toast.makeText(MainActivity.this,"Success",Toast.LENGTH_LONG).show();
        }
        catch (IOException e) {
            // Jibble.
            Toast.makeText(MainActivity.this,"Failed",Toast.LENGTH_LONG).show();
        }
    }
}

总是给我这个错误。当我点击它指向

的错误时

ftp.connect(FTP_HOST,21,FTP_USER,FTP_PASS);

05-08 22:17:43.126 24537-24537/com.amobi.imageuploading E/AndroidRuntime: FATAL EXCEPTION: main
                                                                          android.os.NetworkOnMainThreadException
                                                                              at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
                                                                              at java.net.InetAddress.lookupHostByName(InetAddress.java:385)
                                                                              at java.net.InetAddress.getAllByNameImpl(InetAddress.java:236)
                                                                              at java.net.InetAddress.getAllByName(InetAddress.java:214)
                                                                              at java.net.Socket.tryAllAddresses(Socket.java:108)
                                                                              at java.net.Socket.<init>(Socket.java:177)
                                                                              at java.net.Socket.<init>(Socket.java:149)
                                                                              at org.jibble.simpleftp.SimpleFTP.connect(SimpleFTP.java:68)
                                                                              at com.amobi.imageuploading.MainActivity.uploadFile(MainActivity.java:121)
                                                                              at com.amobi.imageuploading.MainActivity$1.onClick(MainActivity.java:49)
                                                                              at android.view.View.performClick(View.java:4204)
                                                                              at android.view.View$PerformClick.run(View.java:17355)
                                                                              at android.os.Handler.handleCallback(Handler.java:725)
                                                                              at android.os.Handler.dispatchMessage(Handler.java:92)
                                                                              at android.os.Looper.loop(Looper.java:137)
                                                                              at android.app.ActivityThread.main(ActivityThread.java:5041)
                                                                              at java.lang.reflect.Method.invokeNative(Native Method)
                                                                              at java.lang.reflect.Method.invoke(Method.java:511)
                                                                              at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
                                                                              at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
                                                                              at dalvik.system.NativeStart.main(Native Method)

任何人都可以帮我找到导致此错误的原因吗?谢谢

2 个答案:

答案 0 :(得分:1)

将这段代码放在setContentView();

之后
if (android.os.Build.VERSION.SDK_INT > 9) {
    StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
    StrictMode.setThreadPolicy(policy);
}

答案 1 :(得分:0)

您可以阅读有关NetworkOnMainThreadException here的信息。如果您正在使用网络操作,NetworkOnMainThreadException是一个非常流行的例外。