file_upload.c 1.78 KB
Newer Older
Sergey Lyubka's avatar
Sergey Lyubka committed
1 2 3 4 5 6 7
// Copyright (c) 2004-2012 Sergey Lyubka
// This file is a part of mongoose project, http://github.com/valenok/mongoose

#include <stdio.h>
#include <string.h>
#include "mongoose.h"

8
static int send_index_page(struct mg_connection *conn) {
Sergey Lyubka's avatar
Sergey Lyubka committed
9
  const char *data;
10
  int data_len, ofs = 0;
Sergey Lyubka's avatar
Sergey Lyubka committed
11 12 13 14 15 16 17 18 19 20
  char var_name[100], file_name[100];

  mg_printf_data(conn, "%s",
                 "<html><body>Upload example."
                 "<form method=\"POST\" action=\"/handle_post_request\" "
                 "  enctype=\"multipart/form-data\">"
                 "<input type=\"file\" name=\"file\" /> <br/>"
                 "<input type=\"submit\" value=\"Upload\" />"
                 "</form>");

21 22 23 24 25 26
  while ((ofs = mg_parse_multipart(conn->content + ofs, conn->content_len - ofs,
                                   var_name, sizeof(var_name),
                                   file_name, sizeof(file_name),
                                   &data, &data_len)) > 0) {
    mg_printf_data(conn, "var: %s, file_name: %s, size: %d bytes<br>",
                   var_name, file_name, data_len);
Sergey Lyubka's avatar
Sergey Lyubka committed
27
  }
Sergey Lyubka's avatar
Sergey Lyubka committed
28

Sergey Lyubka's avatar
Sergey Lyubka committed
29
  mg_printf_data(conn, "%s", "</body></html>");
30 31

  return MG_TRUE;
32
}
Sergey Lyubka's avatar
Sergey Lyubka committed
33

34
static int ev_handler(struct mg_connection *conn, enum mg_event ev) {
35 36 37 38
  switch (ev) {
    case MG_AUTH:     return MG_TRUE;
    case MG_REQUEST:  return send_index_page(conn);
    default:          return MG_FALSE;
39
  }
40 41
}

Sergey Lyubka's avatar
Sergey Lyubka committed
42
int main(void) {
Sergey Lyubka's avatar
Sergey Lyubka committed
43 44 45
  struct mg_server *server;

  // Create and configure the server
46
  server = mg_create_server(NULL, ev_handler);
Sergey Lyubka's avatar
Sergey Lyubka committed
47 48 49 50 51 52 53 54 55 56
  mg_set_option(server, "listening_port", "8080");

  // Serve request. Hit Ctrl-C to terminate the program
  printf("Starting on port %s\n", mg_get_option(server, "listening_port"));
  for (;;) {
    mg_poll_server(server, 1000);
  }

  // Cleanup, and free server instance
  mg_destroy_server(&server);
Sergey Lyubka's avatar
Sergey Lyubka committed
57 58 59

  return 0;
}