1

I am sending an audio file to my cpprest powered API, and I want to copy that file to a local directory on the server. However, I'm having trouble with actually getting the file from the http_request. I've tried two different approaches which I will outline below.

Approach #1:

auto fileBuffer =
        std::make_shared<Concurrency::streams::basic_ostream<uint8_t>>();
    try
    {
        auto stream = concurrency::streams::fstream::open_ostream(
            U("uploaded.wav"),
            std::ios_base::out | std::ios_base::binary).then([message, fileBuffer](pplx::task<Concurrency::streams::basic_ostream<unsigned char>> Previous_task)
        {

            *fileBuffer = Previous_task.get();
            try
            {
                message.body().read_to_end(fileBuffer->streambuf()).get();
            }
            catch (const exception&)
            {
                wcout << L"<exception>" << std::endl;
            }

        }).then([=](pplx::task<void> Previous_task)
        {
            fileBuffer->close();
        });
    }
    catch (const exception& e)
    {
        wcout << e.what() << endl;
    }

This results in a corrupted file that won't play, but when I open it in notepad I see the following at the top of the file:

------WebKitFormBoundaryHdPc63BmFUcMXB3x
Content-Disposition: form-data; name="uploadFile"; filename="preamble.wav"
Content-Type: audio/wav

If I remove this section, it plays -- so the file is being copied, I'm just adding that extra text from the body at the top of the file. Based on this information, I tried to copy line by line to remove the junk, as follows:

Approach #2:

ofstream outfile;
    const auto data = message.content_ready().get().extract_vector().get();
    std::string body = { data.begin(), data.end() };
    std::istringstream iss(body);
    bool startCopying = false;
    
    std::string line;
    while (std::getline(iss, line)) {
        if (startCopying) {
            outfile << line;
        }
        else if (line == "\r") {
            startCopying = true;
            outfile.open("test.wav");
        }
    }
    outfile.close();

This results in a corrupted file as well; this time the file plays but the audio is replaced by an equal amount of static.

So, how does one typically extract the desired file from http_request body?

0 Answers0