将文件上传到FTP服务器

时间:2011-05-03 15:25:48

标签: android

我正在尝试使用以下代码将文件上传到FTP服务器:

private 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://" );

            if (user != null && password != null){
               sb.append( user );
               sb.append( ':' );
               sb.append( password );
               sb.append( '@' );
            }

            sb.append( ftpServer );
            sb.append( '/' );
            sb.append( fileName );
            sb.append( ";type=i" );

            BufferedInputStream bis = null;
            BufferedOutputStream bos = null;
            try
            {
               URL url = new URL( sb.toString() );
               URLConnection urlc = url.openConnection();
                   urlc.setDoOutput(true);
               bos = new BufferedOutputStream( urlc.getOutputStream() );
               bis = new BufferedInputStream( new FileInputStream( source ) );
               int i;
               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{
            Log.e("Tag", "Input not available." );
         }
    }

但该文件不会在服务器上结束。

2 个答案:

答案 0 :(得分:2)

我不确定您是否可以通过这种方式与FTP服务器通信。 我建议使用apache ftp客户端。

下载 http://commons.apache.org/net/download_net.cgi

文件在 http://commons.apache.org/net/api/org/apache/commons/net/ftp/package-summary.html

答案 1 :(得分:1)

代码看起来正确但您必须添加catch语句来处理异常并确定问题发生的原因。尝试确保至少可以获得输出流。

try
{
    //do some operation
    URL url = new URL(CONNECTION_URL);
    URLConnection urlc = url.openConnection();
    urlc.setDoOutput(true);
    OutputStream outStream = urlc.getOutputStream();

}
catch(IOException ex)
{
    // ** your error information is in ex.getCause () **
}
finally
{
    //clean up
}

<强>替代地

另一种方法是使用来自apache的FTPClient调用,Android - how to upload a file via FTP详细说明使用您的方法的一些困难,并提出同样的建议。它还提供了如何在代码中实现FTPclient的一个很好的示例。