Thursday 20 June 2013

How to upload file to server in android using FTP

In my previous post I have discussed how we can upload file using HTTP-POST method.
It is a good method, but if you have a large file and server is not configured for upload of that size it will fail.
So, we can use another protocol made for transferring files between two machines, FTP. As android app is build using java we can use Apache Commons Net library which provides classes for using FTP service.
You can download it here, and then dd commons-net-3.2 file to your android project. Here is the code to connect to FTP server.
FTPClient client = new FTPClient(); client.connect(FTPSERVER, PORT); client.login(USERNAME, PASSWORD);
Here we instantiate an object of FTPClient class which is used for communication with server.
  • FTPSERVER is address of your ftpp server where you want to upload file
  • PORT is the post used to connect to server, mostly 21
Once you have logged in successfully, you can change current working directory on server, upload file receive file etc.
connect method throws SocketException, IOException and login method throws IOException so you should surround them in try/catch block.
Once you have logged in you can use printWorkingDirectory() method to get the current working directory. It returns path of directory as String.
changeWorkingDirectory(String dir) method is used to change the working directory.

So once you are at your target directory you can upload files. You can upload then as Binary or Text(ASCII) files.
client.setFileType(FTP.BINARY_FILE_TYPE, FTP.BINARY_FILE_TYPE); client.setFileTransferMode(FTP.BINARY_FILE_TYPE);
Or
client.setFileType(FTP.ASCII_FILE_TYPE, FTP.ASCII_FILE_TYPE); client.setFileTransferMode(FTP.ASCII_FILE_TYPE);
Mostly it is better to transfer files in binary mode. To upload a file use
client.storeFile(String REMOTE_FILE_NAME, FileInputStream SROUCE);
It will read data from give FileInputStream and save it on server with the name given as first parameter.

NOTE :
This methods use network so make sure not use them on main thread or UI thread. Either use them in a service or in AsyncTask.
Also don't forget to add android.permission.INTERNET permission in manifest file.
Ads :
Buy Kodak, Canon, Panasonic Cameras on www.ebay.com
Electronics, Cars, Fashion, Collectibles, Coupons and More Online Shopping | eBay
www.ebay.co.uk | www.ebay.com.my

1 comment:

  1. hi thanks but i have question ? i want upload file but not to REMOTE_FILE_NAME how can i do that ? for example create new file

    ReplyDelete