boost::beast::http::request Sending a file as multipart/form-data

2.1k views Asked by At

Just getting in to this using http_client_sync.cpp. I added a little bit of code to use the http::file_body type.

I can't seem to figure out how to get the multipart boundaries inserted. Is there something in particular I need to do to make that happen? When I look at the POST in wireshark, the entire multipart/form data is in one big part. Relevant (I hope) snippet below. Modified from oroginal http_client_sync.cpp.

        // Set up an HTTP POST request message
        http::request<http::file_body> req{http::verb::post, target, version};
        // use the full host:port here
        req.set(http::field::host, fullhost.c_str());
        req.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
        req.set(http::field::accept,"*/*");
        req.set(http::field::content_length,contentLen);
        req.set(http::field::content_type,"multipart/form-data; boundary=fd1c38d86c0a42ac933e7319e51882fd");

        req.body() = std::move(body);

        http::request_serializer<http::file_body,  http::fields> sr{req};

        // Send the HTTP request to the remote host
        http::write(socket, sr);
          

I did also try this, but the result was the same

        size_t len = http::write_header(socket, sr);
        while(len!=0)
        {
            len = http::write_some(socket, sr);
        }

The server I'm talking to is expecting multiple parts.

Many Thanks

1

There are 1 answers

1
H. Egan On

Ok it turns out this is possible, and cured my issue. Probably not the "right" way to do it, but it works.

        size_t len = http::write_header(socket, sr);
        
        // where multipart header is a string containing the first boundary
        // and the content disposition
        boost::asio::write(socket,boost::asio::buffer( multipartHeader));

        while(len!=0)
        {
            len = http::write_some(socket, sr);
        }
        // where multipart trailer is a string containing the final boundary
        boost::asio::write(socket,boost::asio::buffer( multipartTrailer));

Happy to hear better solutions.