upload.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. // Copyright (c) 2004-2012 Sergey Lyubka
  2. // This file is a part of civetweb project, http://github.com/sunsetbrew/civetweb
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <fcntl.h>
  6. #include <stdlib.h>
  7. #ifdef _WIN32
  8. #include <windows.h>
  9. #include <io.h>
  10. #define strtoll strtol
  11. typedef __int64 int64_t;
  12. #else
  13. #include <inttypes.h>
  14. #include <unistd.h>
  15. #endif // !_WIN32
  16. #include "civetweb.h"
  17. static int begin_request_handler(struct mg_connection *conn)
  18. {
  19. if (!strcmp(mg_get_request_info(conn)->uri, "/handle_post_request")) {
  20. mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n\r\n");
  21. mg_upload(conn, "/tmp");
  22. } else {
  23. // Show HTML form. Make sure it has enctype="multipart/form-data" attr.
  24. static const char *html_form =
  25. "<html><body>Upload example."
  26. "<form method=\"POST\" action=\"/handle_post_request\" "
  27. " enctype=\"multipart/form-data\">"
  28. "<input type=\"file\" name=\"file\" /> <br/>"
  29. "<input type=\"submit\" value=\"Upload\" />"
  30. "</form></body></html>";
  31. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  32. "Content-Length: %d\r\n"
  33. "Content-Type: text/html\r\n\r\n%s",
  34. (int) strlen(html_form), html_form);
  35. }
  36. // Mark request as processed
  37. return 1;
  38. }
  39. static void upload_handler(struct mg_connection *conn, const char *path)
  40. {
  41. mg_printf(conn, "Saved [%s]", path);
  42. }
  43. int main(void)
  44. {
  45. struct mg_context *ctx;
  46. const char *options[] = {"listening_ports", "8080", NULL};
  47. struct mg_callbacks callbacks;
  48. memset(&callbacks, 0, sizeof(callbacks));
  49. callbacks.begin_request = begin_request_handler;
  50. callbacks.upload = upload_handler;
  51. ctx = mg_start(&callbacks, NULL, options);
  52. getchar(); // Wait until user hits "enter"
  53. mg_stop(ctx);
  54. return 0;
  55. }