upload.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. // Copyright (c) 2004-2012 Sergey Lyubka
  2. // This file is a part of civetweb project, http://github.com/valenok/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. if (!strcmp(mg_get_request_info(conn)->uri, "/handle_post_request")) {
  19. mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n\r\n");
  20. mg_upload(conn, "/tmp");
  21. } else {
  22. // Show HTML form. Make sure it has enctype="multipart/form-data" attr.
  23. static const char *html_form =
  24. "<html><body>Upload example."
  25. "<form method=\"POST\" action=\"/handle_post_request\" "
  26. " enctype=\"multipart/form-data\">"
  27. "<input type=\"file\" name=\"file\" /> <br/>"
  28. "<input type=\"submit\" value=\"Upload\" />"
  29. "</form></body></html>";
  30. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  31. "Content-Length: %d\r\n"
  32. "Content-Type: text/html\r\n\r\n%s",
  33. (int) strlen(html_form), html_form);
  34. }
  35. // Mark request as processed
  36. return 1;
  37. }
  38. static void upload_handler(struct mg_connection *conn, const char *path) {
  39. mg_printf(conn, "Saved [%s]", path);
  40. }
  41. int main(void) {
  42. struct mg_context *ctx;
  43. const char *options[] = {"listening_ports", "8080", NULL};
  44. struct mg_callbacks callbacks;
  45. memset(&callbacks, 0, sizeof(callbacks));
  46. callbacks.begin_request = begin_request_handler;
  47. callbacks.upload = upload_handler;
  48. ctx = mg_start(&callbacks, NULL, options);
  49. getchar(); // Wait until user hits "enter"
  50. mg_stop(ctx);
  51. return 0;
  52. }