upload.c 1.6 KB

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