FTP – Sample Application & How To Avoid File Corruption When Transfer [Binary vs ASCII]

Through this article I will walk you through a sample FTP client and how to avoid file corruption when transfer.

Recently I came across this issue where some files transferred through FTP got corrupted. After I got to know that some binary files transferred got corrupted when sending through the FTPclient. So I gave a thought to share the findings since it would be more helpful for those who still searching for the solution.

File transfers over FTP handle different forms, basically Binary and ASCII. The main issue is binary file in ASCII mode will corrupt the binary file’s structure and it will convert and encode some characters while transfer.Some FTP clients do not support auto detecting the transfer mode based on the type of the files. But enables manual specification of the mode.

In order to avoid that we need to specify the transfer mode manually when we creating the corresponding FTPClient. So what happen to the ASCII files formats when sending though the binary mode?? Guess what there wont be any issue when transfer because both ASCII and binary files can be sent in binary mode.

ASCII [American Standard Code for Information Interchange] File types

  • HTML files
  • Text files
  • CGI scripts

Ex- .txt .html .shtml .php .pl .cgi .js .css .map .pwd .txt .grp .ctl

Binary File Types

  • zip, tar.gz packages
  • Images
  • File formats such as .doc, .xls

Ex – .jpg .gif .png .tif .exe .zip .sit .rar .class .mid .wav .mp3, .doc, .xls

Sample Application

  •  FTP Server – Apache-Ftpserver-1.0.6
  •  FTP Client – Apache Commons-Net – 2.0

FTPClient


 FTPClient ftpClient = new FTPClient();
 

Connect to the FTP Server


ftpClient.connect(hostname, port);

Check logged in status


boolean isLoggedIn = ftpClient.login(username, password);

To avoid file corruption handle Binary files


ftpClient.setFileTransferMode(FTP.BINARY_FILE_TYPE);
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);

Create FileInputStream from created file.


FileInputStream fileInputStream = new FileInputStream(fileEntry);

Transfer File


boolean isSuccessfullyUploaded = ftpClient.storeFile(upload_path, fileInputStream);

Logout


ftpClient.logout();

Now we have almost completed the FTPClient. Lets check on the FTP Server.

FTP Server

Configure FTP Server

1) Extract the given apache-ftpserver-1.0.6.zip
2) Go to /apache-ftpserver-1.0.6/res/conf
3) Add username and password as available configurations in users.properties (Currently I have configured the username 'local' )

Start FTP server

1) Go to apache-ftpserver-1.0.6/bin/
2) Run ./ftpd.sh res/conf/ftpd-typical.xml

Okay! So now you can test the application by configuring any file type and transfer using Apache FTPClient.

You can download the Sample Application from Github

Hope its helpful for you to implement FTPClient and avoid file corruptions while transfer.

Happy Coding 🙂

Blog Stats

  • 38,691 hits