2

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.

4
  • Read the file into a std::string, pass that instead of a string literal. Commented Oct 22, 2020 at 11:02
  • what if I am not dealing with a text file? lets say, a .jpg or a .db file? Commented Oct 22, 2020 at 13:02
  • Same difference, but make sure to open the file in binary mode. Use this answer as reference Commented Oct 22, 2020 at 13:09
  • Thanks a lot. it worked. That helped a lot. I was stuck for so long trying to understand the documentation! Commented Oct 23, 2020 at 2:01

1 Answer 1

4

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);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.