How to use FTP in Qt (for Windows)

If you are in a situation that you want to upload a file to a FTP server or delete, rename, copy some files on a FTP server in your Qt programs there are no definite choices anywhere. At least that is the case with Qt 5.5. You usually have to use a platform dependent library. So here it is. I use this library when I need FTP access in Qt for Windows. It uses Windows API therefore you won’t be able to use this in Linux or MAC. Download from the link provided below (you may have to register at codeproject.com) and follow the steps to be able to use it in your Qt programs.

1. Download FTP Client class files from here:
http://www.codeproject.com/Articles/8667/FTP-Client-Class

2. Extract all downloaded files to a folder named FtpClient under your project folder.



3. Add the headers and sources to your project by adding the following lines in your Qt PRO file:

SOURCES += FtpClient/BlockingSocket.cpp \
	FtpClient/FTPClient.cpp \
	FtpClient/FTPDataTypes.cpp \
	FtpClient/FTPFileStatus.cpp \
	FtpClient/FTPListParse.cpp

HEADERS += FtpClient/BlockingSocket.h \
	FtpClient/Definements.h \
	FtpClient/FTPClient.h \
	FtpClient/FTPDataTypes.h \
	FtpClient/FTPFileStatus.h \
	FtpClient/FTPListParse.h \
	FtpClient/smart_ptr.h

4. Add Windows Sockets (Winsock) library to your project by adding the following line to your Qt PRO file:

LIBS += -lWs2_32

5. Include the main client class using the following line:

#include "FtpClient/FTPClient.h"


6. I would suggest you to take a look at the simple examples in the article provided for FtpClient. You can use modify and use them in Qt with very minor changes but anyway here is an example of uploading a file to an FTP server. First it tries to delete the existing file. (The same applies to download, rename or any other function.)

nsFTP::CFTPClient ftpClient;
nsFTP::CLogonInfo logonInfo(host_string.toStdWString(),
	21,
	user_string.toStdWString(),
	pass_string.toStdWString());

// connect to server
if (!ftpClient.Login(logonInfo))
{
	QMessageBox::critical(this, "Error", "Can't login!");
	return;
}

// do file operations
if (!ftpClient.Delete(remote_file.toStdWString()))
{
	QMessageBox::warning(this, "Warning", "Can't delete remote file!");
}

if (!ftpClient.UploadFile(QDir().toNativeSeparators(remote_dir).toStdWString(),
	remote_file.toStdWString()))
{
	QMessageBox::critical(this, "Error", "Can't upload!");
}

// disconnect
ftpClient.Logout();

QMessageBox::information(this, "Info", "Finished!");

Good luck!
Post a comment if you have any questions.



Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.