Upload file to FTP server
I'm trying to upload a file to an FTP server with this code:
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 F开发者_运维百科ileInputStream( 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." );
}
}
But the file doesn't end up on the server.
I'm not sure you can communicate with an FTP server in that way. I recommend using the apache ftp client.
Download at http://commons.apache.org/net/download_net.cgi
Documentation at http://commons.apache.org/net/api/org/apache/commons/net/ftp/package-summary.html
The code looks correct but you must add a catch statement to handle exceptions and identify why the problem has occurred. Try making sure that you can at least get the output stream.
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
}
Alternatively
The alternative is to use the FTPClient call from apache, Android - how to upload a file via FTP details some difficulties using your method and makes this same recommendation. It also provides a good example of how to implement FTPclient in your code.
精彩评论