c++httpc++17multipartcpprest-sdk

CppRestSDK How to POST multipart data


I'm trying to POST Multipart data to a server, I'm switching to CPPRestSDK from CPR, but I can't seem to find any documentation on it

Coming from CPR, https://github.com/whoshuu/cpr

Meaning I've tried that code, but I just can't seem to find any documentation on cpprestsdk for multipart data.

    cpr::Multipart multipart_data{};

    for (size_t i = 0; i < files.size(); i++) {
        if (!is_image_or_gif(files[i].filepath)) {
            std::string entire_file = read_entire_file(files[i].filepath);
            std::string custom_filename{ files[i].spoiler ? "SPOILER_" : "" };
            multipart_data.parts.emplace_back(
                "file" + std::to_string(i),
                cpr::Buffer{ entire_file.begin(),
                             entire_file.end(),
                             custom_filename + files[i].filename },
                "application/octet-stream");
        } else {
            multipart_data.parts.emplace_back("file" + std::to_string(i),
                                              cpr::File(files[i].filepath),
                                              "application/octet-stream");
        }
    }

    auto payload_json = nlohmann::json{
        { "content", content },
        { "tts", tts }
    }.dump();
    multipart_data.parts.emplace_back("payload_json", payload_json);

    auto response = cpr::Post(
        cpr::Url{ endpoint("/channels/%/messages", id) },
        cpr::Header{ { "Authorization", format("Bot %", discord::detail::bot_instance->token) },
                     { "Content-Type", "multipart/form-data" },
                     { "User-Agent", "DiscordBot (http://www.github.com/yuhanun/dpp, 0.0.0)" },
                     { "Connection", "keep-alive" } },
        multipart_data);

Where the file struct is quite obvious.

Headers, is fine, i figured that out, I just need some help sending multipart data basically :)

My expected result is to have the server respond with a "success" json, which, in this case is a Message object, of the sent message, however, right now, I don't even know where to start.


Solution

  • Since this is getting some upvotes for some reason, I'd like to answer the question.

    I solved this a long time ago, you can check out my repository to find out how exactly.

    https://github.com/Yuhanun/DPP/blob/master/src/channel.cpp#L108

    https://github.com/Yuhanun/DPP/blob/master/src/utils.cpp#L180

    Enjoy the solution.