upload.c 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  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=\"file\" name=\"file2\" /> <br/>"
  36. "<input type=\"submit\" value=\"Upload\" />"
  37. "</form>"
  38. ""
  39. "</body></html>";
  40. mg_printf(conn, "HTTP/1.0 200 OK\r\n"
  41. "Content-Length: %d\r\n"
  42. "Content-Type: text/html\r\n\r\n%s",
  43. (int) strlen(html_form), html_form);
  44. }
  45. // Mark request as processed
  46. return 1;
  47. }
  48. /* callback: called after uploading a file is completed */
  49. static void upload_handler(struct mg_connection *conn, const char *path)
  50. {
  51. mg_printf(conn, "Saved [%s]", path);
  52. }
  53. /* Main program: Set callbacks and start the server. */
  54. int main(void)
  55. {
  56. /* Test server will use this port */
  57. const char * PORT = "8080";
  58. /* Startup options for the server */
  59. struct mg_context *ctx;
  60. const char *options[] = {
  61. "listening_ports", PORT,
  62. NULL};
  63. struct mg_callbacks callbacks;
  64. memset(&callbacks, 0, sizeof(callbacks));
  65. callbacks.begin_request = begin_request_handler;
  66. callbacks.upload = upload_handler;
  67. /* Display a welcome message */
  68. printf("File upload demo.\n");
  69. printf("Open http://localhost:%s/ im your browser.\n\n", PORT);
  70. /* Start the server */
  71. ctx = mg_start(&callbacks, NULL, options);
  72. /* Wait until thr user hits "enter", then stop the server */
  73. getchar();
  74. mg_stop(ctx);
  75. return 0;
  76. }