jpbarrette/curlpp

FTP upload

nicraMarcin opened this issue · 1 comments

Hi,
could you provide an example of upload to ftp with user and pass?

For anyone looking for an example code for this, here you go:

#include <filesystem>
#include <string>
#include <curlpp/Options.hpp>
#include <curlpp/Easy.hpp>
#include "AutoHandles.hpp"

void upload_via_ftp(const std::filesystem::path& file_path, const std::string& host_name,
    const std::string& remote_file_path, const std::string& username, const std::string& password)
{
    curlpp::Easy request;
    const auto upload_url = "ftp://" + host_name + remote_file_path + "/" + file_path.filename().string();
    request.setOpt(curlpp::options::Url(upload_url));
    request.setOpt(curlpp::options::Upload(true));
    FILE* file_handle{};
    if (const auto error = fopen_s(&file_handle, file_path.string().c_str(), "r");
        error != 0)
    {
        throw std::runtime_error("Failed to open file \"" + file_path.string() + "\" for reading");
    }
    auto auto_file_handle = auto_file_handle_t(file_handle);
    request.setOpt(curlpp::options::ReadFile(file_handle));
    const auto username_password = username + ":" + password;
    request.setOpt(curlpp::options::UserPwd(username_password));
    request.perform();
}

AutoHandles.hpp:

struct opened_file_closer
{
	typedef FILE* pointer;

	void operator()(FILE* handle) const
	{
		if (handle != nullptr)
		{
			fclose(handle);
		}
	}
};

typedef std::unique_ptr<FILE*, opened_file_closer> auto_file_handle_t;