美文网首页
httplib实现文件传输

httplib实现文件传输

作者: 一路向后 | 来源:发表于2022-02-11 21:39 被阅读0次

1.client.c

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "httplib.h"

using namespace std;
using namespace httplib;

int main()
{
    Client cli("http://localhost:1234");

    ifstream fin("./1.txt", ios::binary);
    ostringstream os;
    os << fin.rdbuf();
    string content = os.str();
    cout << content.length() << endl;
    fin.close();

    httplib::MultipartFormDataItems items = {
        {"file", content, "2.txt", "application/octet-stream"}
    };

    auto res = cli.Post("/post", items);

    cout << res->body << endl;

    return 0;
}

2.server.c

#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include "httplib.h"

using namespace std;
using namespace httplib;

int main()
{
    Server svr;

    svr.Post("/post", [](const Request &req, Response &res){
        auto file = req.get_file_value("file");
        char result[256];

        cout << "file name: " << file.filename << endl;
        cout << "file length: " << file.content.length() << endl;

        {
            ofstream ofs(file.filename, ios::binary);

            ofs << file.content;
        }

        sprintf(result, "{ \"code\": 0, \"msg\": \"ok\", \"data\": %d }", (int)file.content.length());

        res.set_content(result, "text/plain");
    });

    svr.listen("localhost", 1234);

    return 0;
}

3.编译源码

$ g++ -o client client.c -std=c++11
$ g++ -o server server.cpp -std=c++11 -lpthread

4.运行及其结果

$ ./server
$ ./client
10
{ "code": 0, "msg": "ok", "data": 10 }

相关文章

网友评论

      本文标题:httplib实现文件传输

      本文链接:https://www.haomeiwen.com/subject/eipzkrtx.html