Boost C++断言失败:body_file_.is_open()和超出了body限制



我是Boost的新手,正在尝试向其中一个客户端示例添加POST请求。但是我未能在服务器端读取http::quest<http::file_body>请求。

Assertion failed: body_.file_.is_open(), file D:Boost C++ ProjectsAsioServreincludeboost _1_72_0boostbeasthttpimplfile_body_win32.hpp, line 184

我阅读了这个file_body_win32.hpp文件中的Boost代码,它只是简单地"告诉"我该文件已打开。为什么?werid的问题是,如果我将content_type: "text/plain"更改为content_type: "image/jpeg"(主体打开图像(,那么断言将被传递,但超出了主体限制。

客户端:

std::string path = "C:\Users\Jinx\Desktop\Damn\test.txt";
body.open(path.c_str(), boost::beast::file_mode::scan, ec);
req_to.version(version);
req_to.method(http::verb::post);
req_to.target(target);
req_to.set(http::field::host, host);
req_to.set(http::field::user_agent, BOOST_BEAST_VERSION_STRING);
req_to.set(http::field::content_type, "text/plain");
req_to.content_length(body.size());
req_to.keep_alive(req_.keep_alive());
req_to.body() = std::move(body);
req_to.prepare_payload();
http::async_write(stream_, req_to, beast::bind_front_handler(&session::on_write, shared_from_this()));

在服务器端,我不知道应该使用什么类型的缓冲区。我试过多缓冲区,但也不起作用。

服务器端:

beast::tcp_stream stream_;
beast::flat_buffer buffer_; 
std::shared_ptr<std::string const> doc_root_;
http::request<http::file_body> req_from;
http::async_read(stream_, buffer_, req_from, beast::bind_front_handler(&session::on_read, shared_from_this()));

根据http::file_body文档:

序列化时,实现将读取文件并将这些八位字节作为正文内容呈现。

服务器如何打开文件?

在服务器端,在调用http::async_read(stream_, buffer_, req_from, beast::bind_front_handler(&session::on_read, shared_from_this()));之前,您必须打开应该向其中写入正文内容的文件。

为此,请执行以下操作:

// Add an error_code, which lives as long as the async operation
boost::beast::error_code ec;
// Then before reading the content of the request do
req_from.body().open("file.jpeg", boost::beast::file_mode::write, ec);
http::async_read(stream_, buffer_, req_from, beast::bind_front_handler(&session::on_read, shared_from_this()));

最新更新