upload.cc 1.0 KB

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