EN ·
🌏 中文

Performing FTP Operations with the POCO Library

About POCO

POCO is a lightweight and flexible network library designed for C++ developers. You can explore the POCO library at its official website: https://pocoproject.org/ or its GitHub project page: https://github.com/pocoproject/poco. You can simply clone the POCO repository and build it by following the official manual. Personally, I built it on Windows using the CMake-GUI tool with all default settings, which worked seamlessly.

How to Upload Files

Necessary Includes

Most FTP-related APIs are located in the Poco/Net/FTPClientSession.h header file. We include exception handling tools as they are essential for robust code. Additionally, when performing an upload to an FTP server, including Poco/StreamCopier.h is mandatory.

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

StreamCopier requires standard streams, so we include those as well:

#include <iostream>
#include <fstream>

Creating the Session Object

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

Performing the 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;
}