upload.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Copyright (c) 2014 the Civetweb developers
  2. * Copyright (c) 2004-2012 Sergey Lyubka
  3. * This file is a part of civetweb project, http://github.com/bel2125/civetweb
  4. */
  5. #include <stdio.h>
  6. #include <string.h>
  7. #include <fcntl.h>
  8. #include <stdlib.h>
  9. #ifdef _WIN32
  10. #include <windows.h>
  11. #include <io.h>
  12. #define strtoll strtol
  13. typedef __int64 int64_t;
  14. #else
  15. #include <inttypes.h>
  16. #include <unistd.h>
  17. #endif // !_WIN32
  18. #include "civetweb.h"
  19. /* callback: used to generate all content */
  20. static int begin_request_handler(struct mg_connection *conn)
  21. {
  22. if (!strcmp(mg_get_request_info(conn)->uri, "/handle_post_request")) {
  23. mg_printf(conn, "%s", "HTTP/1.0 200 OK\r\n\r\n");
  24. mg_upload(conn, "/tmp");
  25. } else {
  26. /* Show HTML form. */
  27. /* See http://www.w3.org/TR/html401/interact/forms.html#h-17.13.4.1 */
  28. static const char *html_form =
  29. "<html><body>Upload example."
  30. ""
  31. /* enctype="multipart/form-data" */
  32. "<form method=\"POST\" action=\"/handle_post_request\" "
  33. " enctype=\"multipart/form-data\">"
  34. "<input type=\"file\" name=\"file\" /> <br/>"
  35. "<input type=\"submit\" value=\"Upload\" />"
  36. "</form>"
  37. ""
  38. "</body></html>";
  39. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  40. "Content-Length: %d\r\n"
  41. "Content-Type: text/html\r\n\r\n%s",
  42. (int) strlen(html_form), html_form);
  43. }
  44. // Mark request as processed
  45. return 1;
  46. }
  47. /* callback: called after uploading a file is completed */
  48. static void upload_handler(struct mg_connection *conn, const char *path)
  49. {
  50. mg_printf(conn, "Saved [%s]", path);
  51. }
  52. /* Main program: Set callbacks and start the server. */
  53. int main(void)
  54. {
  55. /* Test server will use this port */
  56. const char * PORT = "8080";
  57. /* Startup options for the server */
  58. struct mg_context *ctx;
  59. const char *options[] = {
  60. "listening_ports", PORT,
  61. NULL};
  62. struct mg_callbacks callbacks;
  63. memset(&callbacks, 0, sizeof(callbacks));
  64. callbacks.begin_request = begin_request_handler;
  65. callbacks.upload = upload_handler;
  66. /* Display a welcome message */
  67. printf("File upload demo.\n");
  68. printf("Open http://localhost:%s/ im your browser.\n\n", PORT);
  69. /* Start the server */
  70. ctx = mg_start(&callbacks, NULL, options);
  71. /* Wait until thr user hits "enter", then stop the server */
  72. getchar();
  73. mg_stop(ctx);
  74. return 0;
  75. }