1

I found on google this code that basically upload a file to a HTTP Server in Async mode via cpprest. If i have sufficiently enough (i'm newbye to PPL and cpprest and read lots of web pages on msdn) i create a task that open an ifstream from out.txt and then create another task that make a HTTP request with PUT method with file stream as body as input from previous task.

If it's correct... from Server side: 1)how to manage PUT method with a filestream? 2)i need to open a file with the same name of input file,is it possible to extract this info from the body HTTP PUT or i need to put this info inside "out.txt"?

// Upload a file to an HTTP server.
pplx::task<void> UploadFileToHttpServerAsync()
{
    using concurrency::streams::file_stream;
    using concurrency::streams::basic_istream;

    // To run this example, you must have a file named out.txt in the current folder.

    // Open stream to file.
    wstring filePath = L"out.txt";
    return file_stream<unsigned char>::open_istream(L"filePath").then([](pplx::task<basic_istream<unsigned char>> previousTask)
    {
        try
        {
            auto fileStream = previousTask.get();
            http_client client(L"http://localhost:80");
            return client.request(methods::PUT, L"filePath", fileStream).then([fileStream](pplx::task<http_response> previousTask)
            {
                fileStream.close();

                std::wostringstream ss;
                try
                {
                    auto response = previousTask.get();
                    ss << L"Server returned returned status code " << response.status_code() << L"." << std::endl;
                }
                catch (const http_exception& e)
                {
                    ss << e.what() << std::endl;
                }
                std::wcout << ss.str();
            });
        }
        catch (const std::system_error& e)
        {
            std::wostringstream ss;
            ss << e.what() << std::endl;
            std::wcout << ss.str();

            // Return an empty task.
            return pplx::task_from_result();
        }
    });
Jonas
  • 6,915
  • 8
  • 35
  • 53
kenhero
  • 95
  • 2
  • 11
  • I think i solved even if actually i don't know if there is difference between stream.close().wait() and stream.close().get() void handle_post(http_request request) { TRACE("\nhandle POST\n"); auto stream = concurrency::streams::fstream::open_ostream( U("uploaded.txt"), std::ios_base::out | std::ios_base::binary).get(); try { request.body().read_to_end(stream.streambuf()).wait(); stream.close().get(); } catch (http_exception const & e) { wcout << e.what() << endl; } request.reply(status_codes::OK, U("Hello, World!")); } – kenhero Feb 03 '17 at 13:12

0 Answers0