Skip to content Skip to sidebar Skip to footer

Uploading A File To A Ftp Server From Android Phone?

Following is the code that's suppose to create a text document and upload it to my FTP server. For some reason it doesn't seem to work. I used to the libraries provided at http://

Solution 1:

See this...... This will help you rectify the probs in your code.

I have used the apache's commons library to upload and download an Audio file to and from the Server... see this...

Uploading:

publicvoidgoforIt(){


        FTPClientcon=null;

        try
        {
            con = newFTPClient();
            con.connect("192.168.2.57");

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

                FileInputStreamin=newFileInputStream(newFile(data));
                booleanresult= con.storeFile("/vivekm4a.m4a", in);
                in.close();
                if (result) Log.v("upload result", "succeeded");
                con.logout();
                con.disconnect();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }






    }

Downloading:

publicvoidgoforIt(){
    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();
    }



}

Solution 2:

You can use Simple Java FTP Client and add it as external jar for your project, you can also refer to this link

publicclassFileUpload{

   /**
    * 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.
    */publicvoid 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 streamwhile ((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." );
      }
   }

You can also use the Apache commons-net-ftp library, for more details you can focus on this link.

import org.apache.commons.net.ftp.FTPClient;

FTPClientftpClient=newFTPClient();

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);
        BufferedInputStreambuffIn=null;
        buffIn = newBufferedInputStream(newFileInputStream(FULL_PATH_TO_LOCAL_FILE));
        ftpClient.enterLocalPassiveMode();
        ProgressInputStreamprogressInput=newProgressInputStream(buffIn, progressHandler);

        booleanresult= 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());
}

Solution 3:

Here is the code block :

privateclassUploadFileextendsAsyncTask<String, Integer, Boolean> {

    @OverrideprotectedBooleandoInBackground(String... params) {
        FTPClient client = newFTPClient();
        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, newFileInputStream(newFile(
                    params[0])));

        } catch (Exception e) {
            Log.d("FTP", e.toString());
            returnfalse;
        }
    }

    @OverrideprotectedvoidonPostExecute(Boolean sucess) {
        if (sucess)
            Toast.makeText(activity, "File Sent", Toast.LENGTH_LONG).show();
        elseToast.makeText(activity, "Error", Toast.LENGTH_LONG).show();
    }

}

Please get complete working project for uploading files to FTP server from below drive.

File uploading to FTP is used PORT 21, required parameter to upload file on FTP..

host name username password

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

Post a Comment for "Uploading A File To A Ftp Server From Android Phone?"