• cpp-httplib实现文件上传


    上面的静态文件服务实现了文件的下载,下面实现一下文件的上传upload
    参考:examples目录下的upload.cc

    #include <httplib.h>
    #include <iostream>
    #include <fstream>
    
    using namespace httplib;
    using namespace std;
    
    const char *html = R"(
                       <form id="formElem">
                       <input type="file" name="image_file" accept="image/*"><br>
                       <input type="file" name="text_file" accept="text/*"><br>
                       <input type="submit">
                       </form>
                       <script>
                       formElem.onsubmit = async (e) => {
                       e.preventDefault();
                       let res = await fetch('/post', {
                       method: 'POST',
                       body: new FormData(formElem)
                       });
                       console.log(await res.text());
                       };
                       </script>
                       )";
    
    int main(void)
    {
        Server svr;
        svr.set_base_dir("./");
    
        /// upload
        svr.Get("/upload", [](const Request & /*req*/, Response &res) {
            res.set_content(html, "text/html");
        });
    
        svr.Post("/post", [](const Request &req, Response &res) {
            auto image_file = req.get_file_value("image_file");
            auto text_file = req.get_file_value("text_file");
    
            cout << "image file length: " << image_file.content.length() << endl
                 << "image file name: " << image_file.filename << endl
                 << "text file length: " << text_file.content.length() << endl
                 << "text file name: " << text_file.filename << endl;
    
            {
                ofstream ofs(image_file.filename, ios::binary);
                ofs << image_file.content;
            }
            {
                ofstream ofs(text_file.filename);
                ofs << text_file.content;
            }
    
            res.set_content("done", "text/plain");
        });
    
    
        /// listen
        svr.listen("localhost", 1234);
    }

    文件被上传,服务端接收到请求后将文件数据写到文件中去。

  • 相关阅读:
    去除测序reads中的接头:adaptor
    Python学习_13_继承和元类
    Matplotlib初体验
    Python学习_12_方法和类定制
    python+requests接口自动化测试框架实例详解教程
    typeof与instanceof运算符
    闭包与递归函数的区别
    添加SSH
    AndroidStudio常用快捷键总结
    git新建分支
  • 原文地址:https://www.cnblogs.com/MakeView660/p/12779236.html
Copyright © 2020-2023  润新知