upload.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. static void *callback(enum mg_event event, struct mg_connection *conn) {
  18. if (event == MG_NEW_REQUEST) {
  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 as processed
  37. return "";
  38. } else if (event == MG_UPLOAD) {
  39. mg_printf(conn, "Saved [%s]", mg_get_request_info(conn)->ev_data);
  40. }
  41. return NULL;
  42. }
  43. int main(void) {
  44. struct mg_context *ctx;
  45. const char *options[] = {"listening_ports", "8080", NULL};
  46. ctx = mg_start(&callback, NULL, options);
  47. getchar(); // Wait until user hits "enter"
  48. pause();
  49. mg_stop(ctx);
  50. return 0;
  51. }