2011-05-03 218 views
1

我试图将文件上载到与此代码的FTP服务器:上传文件到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."); 
     } 
    } 

但文件没有在服务器上结束。

回答

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的好例子。