【问题标题】:Uploading file using cpp-httplib使用 cpp-httplib 上传文件
【发布时间】:2023-03-19 18:15:01
【问题描述】:

我正在使用 cpp-httplib 并且我正在尝试将文件上传到像 https://ptsv2.com 这样的后期测试服务器。我不太了解有关文件上传的给定文档,我有点理解您必须使用 Multipart/form-data 才能上传文件。

文档中给出的代码是这样的

httplib::MultipartFormDataItems items = {
  { "text1", "text default", "", "" },
  { "text2", "aωb", "", "" },
  { "file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain" },
  { "file2", "{\n  \"world\", true\n}\n", "world.json", "application/json" },
  { "file3", "", "", "application/octet-stream" },
};

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

在file1中你可以看到它正在服务器上创建一个文件并命名为hello.txt。 如何编写它以便我可以将位于我设备上的文件上传到服务器上?

任何建议都会有所帮助。谢谢。

【问题讨论】:

  • Read the file into a std::string,传递它而不是字符串文字。
  • 如果我不处理文本文件怎么办?假设是 .jpg 还是 .db 文件?
  • 相同的区别,但请确保以二进制模式打开文件。使用this answer 作为参考
  • 非常感谢。有效。这有很大帮助。我被困了很长时间试图理解文档!

标签: c++ http http-post


【解决方案1】:

根据@Botje 和 cpp-httplib 文档

std::ifstream t_lf_img("lfimg.png");
std::stringstream buffer_lf_img;
buffer_lf_img << t_lf_img.rdbuf();

std::ifstream t_pc_file("pc.ply");
std::stringstream buffer_pc_file;
buffer_pc_file << t_pc_file.rdbuf();

httplib::Client cliSendFiles("http://ip::port");
httplib::MultipartFormDataItems items = {
        {"files", buffer_lf_img.str(), "lf.png", "application/octet-stream"},
        {"files", buffer_pc_file.str(), "truck.ply", "application/octet-stream"},
};
auto resSendFiles = cliSendFiles.Post("/uploadfile", items);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-14
    • 2011-09-28
    • 2021-03-09
    • 1970-01-01
    • 1970-01-01
    • 2021-11-19
    • 2012-10-22
    相关资源
    最近更新 更多