【问题标题】:Uploading a file to a FTP server from android phone?从安卓手机上传文件到FTP服务器?
【发布时间】:2012-07-21 00:10:47
【问题描述】:

以下是用于创建文本文档并将其上传到我的 FTP 服务器的代码。由于某种原因,它似乎不起作用。我习惯了

提供的库

http://lavalatwork.blogspot.tw/2010/09/using-apache-commons-ftp-library-in.html

用于与 FTP 服务器通信。

try
    {
        final String testString = new String("Hello");
        FileOutputStream fOut = openFileOutput("samplefile.txt",
                MODE_WORLD_READABLE);
        OutputStreamWriter osw = new OutputStreamWriter(fOut); 

        osw.write(testString);
        osw.flush();
        osw.close();
    }


    catch(IOException ex)
    {

    }


    FTPClient mFTP = new FTPClient();
    try {
        // Connect to FTP Server
        mFTP.connect("192.168.10.101");
        //mFTP.login("user", "password");
        mFTP.setFileType(FTP.BINARY_FILE_TYPE);
        mFTP.enterLocalPassiveMode();

        // Prepare file to be uploaded to FTP Server
        File file = new File(getFileStreamPath("samplefile.txt")+ "");
        FileInputStream ifile = new FileInputStream(file);

        // Upload file to FTP Server
        mFTP.storeFile("filetotranfer",ifile);
        mFTP.disconnect();          
    } catch (SocketException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

任何帮助将不胜感激。

【问题讨论】:

  • 在使用 Apache Commons FTP 客户端时检查 logcat 的输出通常很有帮助。
  • 请明确说明什么是行不通的。并发布您的 logcat。

标签: java android ftp apache-commons apache-commons-net


【解决方案1】:

看到这个......这将帮助您纠正代码中的问题。

我已使用 apache 的公共库向服务器上传和下载音频文件...请参阅此...

上传中:

public void goforIt(){


        FTPClient con = null;

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

            if (con.login("Administrator", "KUjWbk"))
            {
                con.enterLocalPassiveMode(); // important!
                con.setFileType(FTP.BINARY_FILE_TYPE);
                String data = "/sdcard/vivekm4a.m4a";

                FileInputStream in = new FileInputStream(new File(data));
                boolean result = con.storeFile("/vivekm4a.m4a", in);
                in.close();
                if (result) Log.v("upload result", "succeeded");
                con.logout();
                con.disconnect();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }






    }

正在下载:

public void goforIt(){
    FTPClient con = null;

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

        if (con.login("Administrator", "KUjWbk"))
        {
            con.enterLocalPassiveMode(); // important!
            con.setFileType(FTP.BINARY_FILE_TYPE);
            String data = "/sdcard/vivekm4a.m4a";

            OutputStream out = new FileOutputStream(new File(data));
            boolean result = con.retrieveFile("vivekm4a.m4a", out);
            out.close();
            if (result) Log.v("download result", "succeeded");
            con.logout();
            con.disconnect();
        }
    }
    catch (Exception e)
    {
        Log.v("download result","failed");
        e.printStackTrace();
    }



}

【讨论】:

    【解决方案2】:

    您可以使用Simple Java FTP Client并将其添加为项目的外部jar,您也可以参考这个link

    public class FileUpload
    {
    
       /**
        * Upload a file to a FTP server. A FTP URL is generated with the
        * following syntax:
        * ftp://user:password@host:port/filePath;type=i.
        *
        * @param ftpServer , FTP server address (optional port ':portNumber').
        * @param user , Optional user name to login.
        * @param password , Optional password for user.
        * @param fileName , Destination file name on FTP server (with optional
        *            preceding relative path, e.g. "myDir/myFile.txt").
        * @param source , Source file to upload.
        * @throws MalformedURLException, IOException on error.
        */
       public void upload( String ftpServer, String user, String password,
             String fileName, File source ) throws MalformedURLException,
             IOException
       {
          if (ftpServer != null && fileName != null && source != null)
          {
             StringBuffer sb = new StringBuffer( "ftp://" );
             // check for authentication else assume its anonymous access.
             if (user != null && password != null)
             {
                sb.append( user );
                sb.append( ':' );
                sb.append( password );
                sb.append( '@' );
             }
             sb.append( ftpServer );
             sb.append( '/' );
             sb.append( fileName );
             /*
              * type ==> a=ASCII mode, i=image (binary) mode, d= file directory
              * listing
              */
             sb.append( ";type=i" );
    
             BufferedInputStream bis = null;
             BufferedOutputStream bos = null;
             try
             {
                URL url = new URL( sb.toString() );
                URLConnection urlc = url.openConnection();
    
                bos = new BufferedOutputStream( urlc.getOutputStream() );
                bis = new BufferedInputStream( new FileInputStream( source ) );
    
                int i;
                // read byte by byte until end of stream
                while ((i = bis.read()) != -1)
                {
                   bos.write( i );
                }
             }
             finally
             {
                if (bis != null)
                   try
                   {
                      bis.close();
                   }
                   catch (IOException ioe)
                   {
                      ioe.printStackTrace();
                   }
                if (bos != null)
                   try
                   {
                      bos.close();
                   }
                   catch (IOException ioe)
                   {
                      ioe.printStackTrace();
                   }
             }
          }
          else
          {
             System.out.println( "Input not available." );
          }
       }
    

    你也可以使用Apache commons-net-ftp库,更多细节可以关注这个link

    import org.apache.commons.net.ftp.FTPClient;
    
    FTPClient ftpClient = new FTPClient();
    
    try {
        ftpClient.connect(InetAddress.getByName(SERVER));
        ftpClient.login(USERNAME, PASSWORD);
        ftpClient.changeWorkingDirectory(PATH);
    
        if (ftpClient.getReplyString().contains("250")) {
            ftpClient.setFileType(org.apache.commons.net.ftp.FTP.BINARY_FILE_TYPE);
            BufferedInputStream buffIn = null;
            buffIn = new BufferedInputStream(new FileInputStream(FULL_PATH_TO_LOCAL_FILE));
            ftpClient.enterLocalPassiveMode();
            ProgressInputStream progressInput = new ProgressInputStream(buffIn, progressHandler);
    
            boolean result = ftpClient.storeFile(localAsset.getFileName(), progressInput);
            buffIn.close();
            ftpClient.logout();
            ftpClient.disconnect();
        }
    
    } catch (SocketException e) {
        Log.e(SorensonApplication.TAG, e.getStackTrace().toString());
    } catch (UnknownHostException e) {
        Log.e(SorensonApplication.TAG, e.getStackTrace().toString());
    } catch (IOException e) {
        Log.e(SorensonApplication.TAG, e.getStackTrace().toString());
    }
    

    【讨论】:

    • 我们是否应该在 Manifest 上设置一些东西以获得互联网连接权限?
    • 出现someSocket问题,是什么意思?
    【解决方案3】:

    这里是代码块:

    private class UploadFile extends AsyncTask<String, Integer, Boolean> {
    
        @Override
        protected Boolean doInBackground(String... params) {
            FTPClient client = new FTPClient();
            try {
                client.connect(params[1], PORT);
                client.login(params[2], params[3]);
                client.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE);
                return client.storeFile(filename, new FileInputStream(new File(
                        params[0])));
    
            } catch (Exception e) {
                Log.d("FTP", e.toString());
                return false;
            }
        }
    
        @Override
        protected void onPostExecute(Boolean sucess) {
            if (sucess)
                Toast.makeText(activity, "File Sent", Toast.LENGTH_LONG).show();
            else
                Toast.makeText(activity, "Error", Toast.LENGTH_LONG).show();
        }
    
    }
    

    请获取完整的工作项目,用于从以下驱动器将文件上传到 FTP 服务器。

    文件上传到 FTP 使用 PORT 21, 在 FTP 上上传文件所需的参数..

    主机名 用户名 密码

    https://drive.google.com/file/d/0B80LBJs3JkaDYUNfZ3pDSkVJUDA/edit

    【讨论】:

    • 谢谢@FelixSFD 我已经编辑了我的答案,请调查一下。现在还好吗?
    猜你喜欢
    • 2011-11-16
    • 2011-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多