【问题标题】:Android Uploading image to ftp server not workingAndroid将图像上传到ftp服务器不起作用
【发布时间】:2017-06-11 01:07:27
【问题描述】:

嘿,我正在尝试将图像上传到我的 ftp 服务器,但由于某种原因,连接无法正常工作,我可以找出原因..

这里是连接代码:

 public  void uploadingFilestoFtp() throws IOException {
    FTPClient ftpclient = new FTPClient();
    FileInputStream fis = null;
    boolean result;


    try {
        ftpclient.connect(host);

        result = ftpclient.login(username, password);

        if (result == true) {
            System.out.println("Logged in Successfully !");
        } else {
            System.out.println("Login Fail!");
            return;
        }
        ftpclient.setFileType(FTP.BINARY_FILE_TYPE);

        ftpclient.changeWorkingDirectory("/");

        File file = new File(imagePath);
        fis = new FileInputStream(file);

        // Upload file to the ftp serverresult = ftpclient.storeFile(testName, fis);

        if (result == true) {
            System.out.println("File is uploaded successfully");
        } else {
            System.out.println("File uploading failed");
        }
        ftpclient.logout();
    } catch (FTPConnectionClosedException e) {
        e.printStackTrace();
    } finally {
        try {
            ftpclient.disconnect();
        } catch (FTPConnectionClosedException e) {
            System.out.println(e);
        }
    }
}

我正在使用 ftp 服务器的详细信息,但它似乎不起作用

我怎样才能让这个方法起作用?

【问题讨论】:

    标签: java android upload ftp ftp-client


    【解决方案1】:
    android.os.NetworkOnMainThreadException
    

    您正在尝试从 UI 线程发出网络请求。 Android 不允许来自主(UI)线程的任何网络请求。您需要创建一个扩展 AsyncTask 的类。

    public class UploadFileTask extends AsyncTask <Void, Void, Void > {
    
        public void onPreExecute() {
    
        }
    
        public void doInBackground(Void...unused) {
            uploadingFilestoFtp(); //Call your method here. Put necessary try-catch block.
        }
    
        public void onPostExecute(Void unused) {
            // do something when upload is done.
        }
    }
    

    请注意,onPreExecute() 和 onPostExecute() 在 UI 线程上运行。所以你可以在网络调用之前或之后做任何事情。在doInBackground()方法中进行网络调用。

    查看这个答案How to fix android.os.NetworkOnMainThreadException?

    【讨论】:

      猜你喜欢
      • 2015-02-23
      • 2012-03-10
      • 1970-01-01
      • 1970-01-01
      • 2018-09-27
      • 2019-09-14
      • 2020-04-29
      • 2017-06-09
      • 1970-01-01
      相关资源
      最近更新 更多