устанавливаем буст
Код: Выделить всё
sudo apt-get install libboost-all-dev
Код: Выделить всё
#include <boost/asio.hpp>
#include <boost/beast.hpp>
#include <boost/filesystem.hpp>
#include <fstream>
#include <iostream>
namespace beast = boost::beast;
namespace http = beast::http;
namespace net = boost::asio;
using tcp = boost::asio::ip::tcp;
// Функция для обработки загрузки файлов
void handle_file_upload(http::request<http::string_body> req, beast::tcp_stream& stream) {
// Извлечение содержимого файла
auto body = req.body();
// Сохранение файла
std::ofstream ofs("uploaded_file.txt", std::ios::out | std::ios::binary);
if (ofs.is_open()) {
ofs << body;
ofs.close();
// Формируем ответ
http::response<http::string_body> res(http::status::ok, req.version());
res.set(http::field::server, "Boost.Beast");
res.set(http::field::content_type, "text/html");
res.body() = "File uploaded successfully.";
res.prepare_payload();
// Отправляем ответ клиенту
http::write(stream, res);
} else {
// Ошибка при открытии файла
http::response<http::string_body> res(http::status::internal_server_error, req.version());
res.set(http::field::server, "Boost.Beast");
res.set(http::field::content_type, "text/html");
res.body() = "Failed to save file.";
res.prepare_payload();
http::write(stream, res);
}
}
// Асинхронный прием запросов
void do_session(tcp::socket socket) {
beast::tcp_stream stream(std::move(socket));
for(;;) {
// Буфер для хранения данных
beast::flat_buffer buffer;
// Чтение запроса
http::request<http::string_body> req;
http::read(stream, buffer, req);
// Обработка только POST запросов
if (req.method() == http::verb::post) {
handle_file_upload(req, stream);
} else {
// Возврат ошибки для не-пост запросов
http::response<http::string_body> res(http::status::method_not_allowed, req.version());
res.set(http::field::server, "Boost.Beast");
res.set(http::field::content_type, "text/html");
res.body() = "Only POST requests are allowed.";
res.prepare_payload();
http::write(stream, res);
}
// Закрываем соединение после обработки запроса
break;
}
}
int main() {
try {
// Устанавливаем контекст для сервера
net::io_context ioc;
// Слушаем на порту 8080
tcp::acceptor acceptor(ioc, {tcp::v4(), 8080});
for(;;) {
// Принимаем новое соединение
tcp::socket socket = acceptor.accept();
std::thread(do_session, std::move(socket)).detach();
}
} catch (std::exception& e) {
std::cerr << "Error: " << e.what() << std::endl;
}
return 0;
}
Код: Выделить всё
g++ -std=c++11 server.cpp -o server -lpthread -lboost_system -lboost_filesystem
Код: Выделить всё
./server
Код: Выделить всё
curl -X POST --data-binary "@/path/to/your/file" http://localhost:8080/
Обратите внимание, что данный пример основан на простоте и не учитывает многие аспекты, такие как обработка ошибок, безопасность и масштабируемость.
Для применения в реальных проектах, вы можете рассмотреть использование более полных решений, таких как cpprestsdk, Crow или другие веб-фреймворки для C++.