Skip to main content

How to Implement FTP Upload by C++ and POCO

BigBookLess than 1 minuteFTPpocoC/C++

POCO

POCO is a lightweight and flexible network library for C++ users.
You can refer to the POCO library at its homepage: https://pocoproject.org/open in new window or its github project page: https://github.com/pocoproject/pocoopen in new window .
You can simply git clone from the POCO repository, and build it follows its official mannual.
For me, I built it simply with the CMake-GUI tool on Windows, with all default settings.

How to Upload

Includes Stuffs

Most of the FTP related APIs are in the Poco/Net/FTPClientSession.h header file. The Exception Processing tools are used all the time, so that we include it too. When you need to do the uploading to FTP server, Poco/StreamCopier.h is must be included.

#include "Poco/Net/FTPClientSession.h"
#include "Poco/Net/NetException.h"
#include "Poco/StreamCopier.h"

The StreamCopier need the std streams, so we include them too.

#include <iostream>
#include <fstream>

Create an Object

auto* ftp = new Poco::Net::FTPClientSession("192.168.1.3", 21, "username", "password");

Do Upload.

try{
    std::ostream &ftpOStream = ftp->beginUpload("target_file_name.png");
    std::ifstream localIFStream("/path/to/local_file.png", std::ifstream::in | std::ifstream::binary);
    auto numBytes = Poco::StreamCopier::copyStream(localIFStream, ftpOStream);
    ftp->endUpload();
}
catch( Poco::Net::FTPException& e)
{
    std::cerr<<e.what()<<e.message()<<std::endl;
}
Last update:
Contributors: Xuling Chang