upload.cc 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. //
  2. // upload.cc
  3. //
  4. // Copyright (c) 2019 Yuji Hirose. All rights reserved.
  5. // MIT License
  6. //
  7. #include <fstream>
  8. #include <httplib.h>
  9. #include <iostream>
  10. using namespace httplib;
  11. using namespace std;
  12. const char *html = R"(
  13. <form id="formElem">
  14. <input type="file" name="image_file" accept="image/*">
  15. <input type="file" name="text_file" accept="text/*">
  16. <input type="submit">
  17. </form>
  18. <script>
  19. formElem.onsubmit = async (e) => {
  20. e.preventDefault();
  21. let res = await fetch('/post', {
  22. method: 'POST',
  23. body: new FormData(formElem)
  24. });
  25. console.log(await res.text());
  26. };
  27. </script>
  28. )";
  29. int main(void) {
  30. Server svr;
  31. svr.Get("/", [](const Request & /*req*/, Response &res) {
  32. res.set_content(html, "text/html");
  33. });
  34. svr.Post("/post", [](const Request &req, Response &res) {
  35. auto image_file = req.get_file_value("image_file");
  36. auto text_file = req.get_file_value("text_file");
  37. cout << "image file length: " << image_file.content.length() << endl
  38. << "image file name: " << image_file.filename << endl
  39. << "text file length: " << text_file.content.length() << endl
  40. << "text file name: " << text_file.filename << endl;
  41. {
  42. ofstream ofs(image_file.filename, ios::binary);
  43. ofs << image_file.content;
  44. }
  45. {
  46. ofstream ofs(text_file.filename);
  47. ofs << text_file.content;
  48. }
  49. res.set_content("done", "text/plain");
  50. });
  51. svr.listen("localhost", 1234);
  52. }