0

I am using cpp-httplib and I am trying to upload a file to a post test server like https://ptsv2.com . I do not really understand the given documentation on file uploads, I somewhat understand that you have to make use of Multipart/form-data in order to upload a file.

The given code in the documentation is this

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);

in file1 you can see that it is creating a file on the server and naming it hello.txt. How do I write it so that I can upload a file that is located on my device onto a server?

Any advice would be helpful. Thank you.

  • [Read the file into a `std::string`](https://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring), pass that instead of a string literal. – Botje Oct 22 '20 at 11:02
  • what if I am not dealing with a text file? lets say, a .jpg or a .db file? – newbies123 Oct 22 '20 at 13:02
  • Same difference, but make sure to open the file in binary mode. Use [this answer](https://stackoverflow.com/a/2602258/1548468) as reference – Botje Oct 22 '20 at 13:09
  • Thanks a lot. it worked. That helped a lot. I was stuck for so long trying to understand the documentation! – newbies123 Oct 23 '20 at 02:01

1 Answers1

0

according to @Botje and cpp-httplib documentation

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);
Walden
  • 1
  • 1