温馨提示×

c++ post如何实现文件上传

c++
小樊
81
2024-07-05 20:13:37
栏目: 编程语言

要实现文件上传功能,可以使用C++编写一个简单的HTTP服务器,接收客户端上传的文件并保存到服务器端。

以下是一个简单的C++ HTTP服务器示例代码,可以实现文件上传功能:

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <boost/asio.hpp>

using namespace boost::asio;
using namespace boost::asio::ip;

class HttpServer {
public:
    HttpServer(io_service& io, short port)
        : acceptor_(io, tcp::endpoint(tcp::v4(), port)),
        socket_(io) {
        acceptor_.accept(socket_);
        handle_request();
    }

private:
    void handle_request() {
        boost::system::error_code error;
        streambuf request;
        read_until(socket_, request, "\r\n\r\n", error);

        std::istream request_stream(&request);
        std::string header;
        getline(request_stream, header);

        std::string method, path, version;
        request_stream >> method >> path >> version;

        if (method == "POST") {
            std::string line;
            while (getline(request_stream, line) && line != "") {
                if (line.find("Content-Length:") != std::string::npos) {
                    std::istringstream iss(line);
                    std::string content_length_str;
                    iss >> content_length_str >> content_length_;
                }
            }

            std::vector<char> body(content_length_);
            socket_.read_some(buffer(body), error);

            std::ofstream file("uploaded_file", std::ios::binary);
            file.write(&body[0], content_length_);
            file.close();
        }

        std::ostream response_stream(&response_);
        response_stream << "HTTP/1.1 200 OK\r\n";
        response_stream << "Content-Length: 0\r\n";
        response_stream << "\r\n";

        write(socket_, response_);
    }

    tcp::acceptor acceptor_;
    tcp::socket socket_;
    boost::asio::streambuf response_;
    size_t content_length_;
};

int main() {
    io_service io;
    HttpServer server(io, 8080);
    io.run();

    return 0;
}

在上面的代码中,我们创建了一个简单的HTTP服务器,监听8080端口。当接收到客户端的POST请求时,服务器会从请求中读取上传的文件内容并保存到服务器端的uploaded_file文件中。

要测试文件上传功能,可以使用curl命令发送POST请求:

curl -X POST -H "Content-Type: application/octet-stream" --data-binary @file.txt http://localhost:8080

上面的命令会将file.txt文件上传到我们的HTTP服务器,并保存到服务器端的uploaded_file文件中。

请注意,以上代码仅为演示目的,实际生产环境中需要添加更多的错误处理和安全性检查。

0