Merge branch 'feature/http_server_wildcard_uri' into 'master'

Wildcard URI matching for http_server

See merge request idf/esp-idf!3973
This commit is contained in:
Ivan Grokhotkov 2019-01-14 19:44:54 +08:00
commit 1ee729336f
16 changed files with 1145 additions and 87 deletions

View File

@ -49,6 +49,7 @@ initializer that should be kept in sync
.global_transport_ctx_free_fn = NULL, \
.open_fn = NULL, \
.close_fn = NULL, \
.uri_match_fn = NULL \
}
#define ESP_ERR_HTTPD_BASE (0x8000) /*!< Starting number of HTTPD error codes */
@ -61,6 +62,10 @@ initializer that should be kept in sync
#define ESP_ERR_HTTPD_ALLOC_MEM (ESP_ERR_HTTPD_BASE + 7) /*!< Failed to dynamically allocate memory for resource */
#define ESP_ERR_HTTPD_TASK (ESP_ERR_HTTPD_BASE + 8) /*!< Failed to launch server task/thread */
/* Symbol to be used as length parameter in httpd_resp_send APIs
* for setting buffer length to string length */
#define HTTPD_RESP_USE_STRLEN -1
/* ************** Group: Initialization ************** */
/** @name Initialization
* APIs related to the Initialization of the web server
@ -82,7 +87,7 @@ typedef enum http_method httpd_method_t;
/**
* @brief Prototype for freeing context data (if any)
* @param[in] ctx : object to free
* @param[in] ctx object to free
*/
typedef void (*httpd_free_ctx_fn_t)(void *ctx);
@ -92,8 +97,8 @@ typedef void (*httpd_free_ctx_fn_t)(void *ctx);
* Called immediately after the socket was opened to set up the send/recv functions and
* other parameters of the socket.
*
* @param[in] hd : server instance
* @param[in] sockfd : session socket file descriptor
* @param[in] hd server instance
* @param[in] sockfd session socket file descriptor
* @return status
*/
typedef esp_err_t (*httpd_open_func_t)(httpd_handle_t hd, int sockfd);
@ -104,11 +109,26 @@ typedef esp_err_t (*httpd_open_func_t)(httpd_handle_t hd, int sockfd);
* @note It's possible that the socket descriptor is invalid at this point, the function
* is called for all terminated sessions. Ensure proper handling of return codes.
*
* @param[in] hd : server instance
* @param[in] sockfd : session socket file descriptor
* @param[in] hd server instance
* @param[in] sockfd session socket file descriptor
*/
typedef void (*httpd_close_func_t)(httpd_handle_t hd, int sockfd);
/**
* @brief Function prototype for URI matching.
*
* @param[in] reference_uri URI/template with respect to which the other URI is matched
* @param[in] uri_to_match URI/template being matched to the reference URI/template
* @param[in] match_upto For specifying the actual length of `uri_to_match` up to
* which the matching algorithm is to be applied (The maximum
* value is `strlen(uri_to_match)`, independent of the length
* of `reference_uri`)
* @return true on match
*/
typedef bool (*httpd_uri_match_func_t)(const char *reference_uri,
const char *uri_to_match,
size_t match_upto);
/**
* @brief HTTP Server Configuration Structure
*
@ -195,6 +215,24 @@ typedef struct httpd_config {
* was closed by the network stack - that is, the file descriptor may not be valid anymore.
*/
httpd_close_func_t close_fn;
/**
* URI matcher function.
*
* Called when searching for a matching URI:
* 1) whose request handler is to be executed right
* after an HTTP request is successfully parsed
* 2) in order to prevent duplication while registering
* a new URI handler using `httpd_register_uri_handler()`
*
* Available options are:
* 1) NULL : Internally do basic matching using `strncmp()`
* 2) `httpd_uri_match_wildcard()` : URI wildcard matcher
*
* Users can implement their own matching functions (See description
* of the `httpd_uri_match_func_t` function prototype)
*/
httpd_uri_match_func_t uri_match_fn;
} httpd_config_t;
/**
@ -227,8 +265,8 @@ typedef struct httpd_config {
*
* @endcode
*
* @param[in] config : Configuration for new instance of the server
* @param[out] handle : Handle to newly created instance of the server. NULL on error
* @param[in] config Configuration for new instance of the server
* @param[out] handle Handle to newly created instance of the server. NULL on error
* @return
* - ESP_OK : Instance created successfully
* - ESP_ERR_INVALID_ARG : Null argument(s)
@ -451,11 +489,11 @@ esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char* uri);
* HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
* return value of httpd_send() function
*
* @param[in] hd : server instance
* @param[in] sockfd : session socket file descriptor
* @param[in] buf : buffer with bytes to send
* @param[in] buf_len : data size
* @param[in] flags : flags for the send() function
* @param[in] hd server instance
* @param[in] sockfd session socket file descriptor
* @param[in] buf buffer with bytes to send
* @param[in] buf_len data size
* @param[in] flags flags for the send() function
* @return
* - Bytes : The number of bytes sent successfully
* - HTTPD_SOCK_ERR_INVALID : Invalid arguments
@ -472,11 +510,11 @@ typedef int (*httpd_send_func_t)(httpd_handle_t hd, int sockfd, const char *buf,
* HTTPD_SOCK_ERR_ codes, which will eventually be conveyed as
* return value of httpd_req_recv() function
*
* @param[in] hd : server instance
* @param[in] sockfd : session socket file descriptor
* @param[in] buf : buffer with bytes to send
* @param[in] buf_len : data size
* @param[in] flags : flags for the send() function
* @param[in] hd server instance
* @param[in] sockfd session socket file descriptor
* @param[in] buf buffer with bytes to send
* @param[in] buf_len data size
* @param[in] flags flags for the send() function
* @return
* - Bytes : The number of bytes received successfully
* - 0 : Buffer length parameter is zero / connection closed by peer
@ -494,8 +532,8 @@ typedef int (*httpd_recv_func_t)(httpd_handle_t hd, int sockfd, char *buf, size_
* HTTPD_SOCK_ERR_ codes, which will be handled accordingly in
* the server task.
*
* @param[in] hd : server instance
* @param[in] sockfd : session socket file descriptor
* @param[in] hd server instance
* @param[in] sockfd session socket file descriptor
* @return
* - Bytes : The number of bytes waiting to be received
* - HTTPD_SOCK_ERR_INVALID : Invalid arguments
@ -744,6 +782,30 @@ esp_err_t httpd_req_get_url_query_str(httpd_req_t *r, char *buf, size_t buf_len)
*/
esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, size_t val_size);
/**
* @brief Test if a URI matches the given wildcard template.
*
* Template may end with "?" to make the previous character optional (typically a slash),
* "*" for a wildcard match, and "?*" to make the previous character optional, and if present,
* allow anything to follow.
*
* Example:
* - * matches everything
* - /foo/? matches /foo and /foo/
* - /foo/\* (sans the backslash) matches /foo/ and /foo/bar, but not /foo or /fo
* - /foo/?* or /foo/\*? (sans the backslash) matches /foo/, /foo/bar, and also /foo, but not /foox or /fo
*
* The special characters "?" and "*" anywhere else in the template will be taken literally.
*
* @param[in] template URI template (pattern)
* @param[in] uri URI to be matched
* @param[in] len how many characters of the URI buffer to test
* (there may be trailing query string etc.)
*
* @return true if a match was found
*/
bool httpd_uri_match_wildcard(const char *template, const char *uri, size_t len);
/**
* @brief API to send a complete HTTP response.
*
@ -772,7 +834,7 @@ esp_err_t httpd_query_key_value(const char *qry, const char *key, char *val, siz
*
* @param[in] r The request being responded to
* @param[in] buf Buffer from where the content is to be fetched
* @param[in] buf_len Length of the buffer, -1 to use strlen()
* @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
*
* @return
* - ESP_OK : On successfully sending the response packet
@ -811,7 +873,7 @@ esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len);
*
* @param[in] r The request being responded to
* @param[in] buf Pointer to a buffer that stores the data
* @param[in] buf_len Length of the data from the buffer that should be sent out, -1 to use strlen()
* @param[in] buf_len Length of the buffer, HTTPD_RESP_USE_STRLEN to use strlen()
*
* @return
* - ESP_OK : On successfully sending the response packet chunk
@ -822,6 +884,48 @@ esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len);
*/
esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len);
/**
* @brief API to send a complete string as HTTP response.
*
* This API simply calls http_resp_send with buffer length
* set to string length assuming the buffer contains a null
* terminated string
*
* @param[in] r The request being responded to
* @param[in] str String to be sent as response body
*
* @return
* - ESP_OK : On successfully sending the response packet
* - ESP_ERR_INVALID_ARG : Null request pointer
* - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
* - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
* - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
*/
inline esp_err_t httpd_resp_sendstr(httpd_req_t *r, const char *str) {
return httpd_resp_send(r, str, (str == NULL) ? 0 : strlen(str));
}
/**
* @brief API to send a string as an HTTP response chunk.
*
* This API simply calls http_resp_send_chunk with buffer length
* set to string length assuming the buffer contains a null
* terminated string
*
* @param[in] r The request being responded to
* @param[in] str String to be sent as response body (NULL to finish response packet)
*
* @return
* - ESP_OK : On successfully sending the response packet
* - ESP_ERR_INVALID_ARG : Null request pointer
* - ESP_ERR_HTTPD_RESP_HDR : Essential headers are too large for internal buffer
* - ESP_ERR_HTTPD_RESP_SEND : Error in raw send
* - ESP_ERR_HTTPD_INVALID_REQ : Invalid request
*/
inline esp_err_t httpd_resp_sendstr_chunk(httpd_req_t *r, const char *str) {
return httpd_resp_send_chunk(r, str, (str == NULL) ? 0 : strlen(str));
}
/* Some commonly used status codes */
#define HTTPD_200 "200 OK" /*!< HTTP Response 200 */
#define HTTPD_204 "204 No Content" /*!< HTTP Response 204 */

View File

@ -246,7 +246,9 @@ esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len)
const char *colon_separator = ": ";
const char *cr_lf_seperator = "\r\n";
if (buf_len == -1) buf_len = strlen(buf);
if (buf_len == HTTPD_RESP_USE_STRLEN) {
buf_len = strlen(buf);
}
/* Request headers are no longer available */
ra->req_hdrs_count = 0;
@ -306,7 +308,9 @@ esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len
return ESP_ERR_HTTPD_INVALID_REQ;
}
if (buf_len == -1) buf_len = strlen(buf);
if (buf_len == HTTPD_RESP_USE_STRLEN) {
buf_len = strlen(buf);
}
struct httpd_req_aux *ra = r->aux;
const char *httpd_chunked_hdr_str = "HTTP/1.1 %s\r\nContent-Type: %s\r\nTransfer-Encoding: chunked\r\n";

View File

@ -23,20 +23,112 @@
static const char *TAG = "httpd_uri";
static int httpd_find_uri_handler(struct httpd_data *hd,
const char* uri,
httpd_method_t method)
static bool httpd_uri_match_simple(const char *uri1, const char *uri2, size_t len2)
{
return strlen(uri1) == len2 && // First match lengths
(strncmp(uri1, uri2, len2) == 0); // Then match actual URIs
}
bool httpd_uri_match_wildcard(const char *template, const char *uri, size_t len)
{
const size_t tpl_len = strlen(template);
size_t exact_match_chars = tpl_len;
/* Check for trailing question mark and asterisk */
const char last = (const char) (tpl_len > 0 ? template[tpl_len - 1] : 0);
const char prevlast = (const char) (tpl_len > 1 ? template[tpl_len - 2] : 0);
const bool asterisk = last == '*' || (prevlast == '*' && last == '?');
const bool quest = last == '?' || (prevlast == '?' && last == '*');
/* Minimum template string length must be:
* 0 : if neither of '*' and '?' are present
* 1 : if only '*' is present
* 2 : if only '?' is present
* 3 : if both are present
*
* The expression (asterisk + quest*2) serves as a
* case wise generator of these length values
*/
/* abort in cases such as "?" with no preceding character (invalid template) */
if (exact_match_chars < asterisk + quest*2) {
return false;
}
/* account for special characters and the optional character if "?" is used */
exact_match_chars -= asterisk + quest*2;
if (len < exact_match_chars) {
return false;
}
if (!quest) {
if (!asterisk && len != exact_match_chars) {
/* no special characters and different length - strncmp would return false */
return false;
}
/* asterisk allows arbitrary trailing characters, we ignore these using
* exact_match_chars as the length limit */
return (strncmp(template, uri, exact_match_chars) == 0);
} else {
/* question mark present */
if (len > exact_match_chars && template[exact_match_chars] != uri[exact_match_chars]) {
/* the optional character is present, but different */
return false;
}
if (strncmp(template, uri, exact_match_chars) != 0) {
/* the mandatory part differs */
return false;
}
/* Now we know the URI is longer than the required part of template,
* the mandatory part matches, and if the optional character is present, it is correct.
* Match is OK if we have asterisk, i.e. any trailing characters are OK, or if
* there are no characters beyond the optional character. */
return asterisk || len <= exact_match_chars + 1;
}
}
/* Find handler with matching URI and method, and set
* appropriate error code if URI or method not found */
static httpd_uri_t* httpd_find_uri_handler(struct httpd_data *hd,
const char *uri, size_t uri_len,
httpd_method_t method,
httpd_err_resp_t *err)
{
if (err) {
*err = HTTPD_404_NOT_FOUND;
}
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
if (hd->hd_calls[i]) {
ESP_LOGD(TAG, LOG_FMT("[%d] = %s"), i, hd->hd_calls[i]->uri);
if ((hd->hd_calls[i]->method == method) && // First match methods
(strcmp(hd->hd_calls[i]->uri, uri) == 0)) { // Then match uri strings
return i;
if (!hd->hd_calls[i]) {
break;
}
ESP_LOGD(TAG, LOG_FMT("[%d] = %s"), i, hd->hd_calls[i]->uri);
/* Check if custom URI matching function is set,
* else use simple string compare */
if (hd->config.uri_match_fn ?
hd->config.uri_match_fn(hd->hd_calls[i]->uri, uri, uri_len) :
httpd_uri_match_simple(hd->hd_calls[i]->uri, uri, uri_len)) {
/* URIs match. Now check if method is supported */
if (hd->hd_calls[i]->method == method) {
/* Match found! */
if (err) {
/* Unset any error that may
* have been set earlier */
*err = 0;
}
return hd->hd_calls[i];
}
/* URI found but method not allowed.
* If URI is found later then this
* error must be set to 0 */
if (err) {
*err = HTTPD_405_METHOD_NOT_ALLOWED;
}
}
}
return -1;
return NULL;
}
esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
@ -48,11 +140,13 @@ esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
struct httpd_data *hd = (struct httpd_data *) handle;
/* Make sure another handler with same URI and method
* is not already registered
*/
/* Make sure another handler with matching URI and method
* is not already registered. This will also catch cases
* when a registered URI wildcard pattern already accounts
* for the new URI being registered */
if (httpd_find_uri_handler(handle, uri_handler->uri,
uri_handler->method) != -1) {
strlen(uri_handler->uri),
uri_handler->method, NULL) != NULL) {
ESP_LOGW(TAG, LOG_FMT("handler %s with method %d already registered"),
uri_handler->uri, uri_handler->method);
return ESP_ERR_HTTPD_HANDLER_EXISTS;
@ -95,15 +189,30 @@ esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle,
}
struct httpd_data *hd = (struct httpd_data *) handle;
int i = httpd_find_uri_handler(hd, uri, method);
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
if (!hd->hd_calls[i]) {
break;
}
if ((hd->hd_calls[i]->method == method) && // First match methods
(strcmp(hd->hd_calls[i]->uri, uri) == 0)) { // Then match URI string
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
if (i != -1) {
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
free((char*)hd->hd_calls[i]->uri);
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
free((char*)hd->hd_calls[i]->uri);
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
return ESP_OK;
/* Shift the remaining non null handlers in the array
* forward by 1 so that order of insertion is maintained */
for (i += 1; i < hd->config.max_uri_handlers; i++) {
if (!hd->hd_calls[i]) {
break;
}
hd->hd_calls[i-1] = hd->hd_calls[i];
}
/* Nullify the following non null entry */
hd->hd_calls[i-1] = NULL;
return ESP_OK;
}
}
ESP_LOGW(TAG, LOG_FMT("handler %s with method %d not found"), uri, method);
return ESP_ERR_NOT_FOUND;
@ -118,17 +227,31 @@ esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri)
struct httpd_data *hd = (struct httpd_data *) handle;
bool found = false;
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
if ((hd->hd_calls[i] != NULL) &&
(strcmp(hd->hd_calls[i]->uri, uri) == 0)) {
int i = 0, j = 0; // For keeping count of removed entries
for (; i < hd->config.max_uri_handlers; i++) {
if (!hd->hd_calls[i]) {
break;
}
if (strcmp(hd->hd_calls[i]->uri, uri) == 0) { // Match URI strings
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, uri);
free((char*)hd->hd_calls[i]->uri);
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
found = true;
j++; // Update count of removed entries
} else {
/* Shift the remaining non null handlers in the array
* forward by j so that order of insertion is maintained */
hd->hd_calls[i-j] = hd->hd_calls[i];
}
}
/* Nullify the following non null entries */
for (int k = (i - j); k < i; k++) {
hd->hd_calls[k] = NULL;
}
if (!found) {
ESP_LOGW(TAG, LOG_FMT("no handler found for URI %s"), uri);
}
@ -138,45 +261,15 @@ esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri)
void httpd_unregister_all_uri_handlers(struct httpd_data *hd)
{
for (unsigned i = 0; i < hd->config.max_uri_handlers; i++) {
if (hd->hd_calls[i]) {
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
free((char*)hd->hd_calls[i]->uri);
free(hd->hd_calls[i]);
if (!hd->hd_calls[i]) {
break;
}
}
}
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
/* Alternate implmentation of httpd_find_uri_handler()
* which takes a uri_len field. This is useful when the URI
* string contains extra parameters that are not to be included
* while matching with the registered URI_handler strings
*/
static httpd_uri_t* httpd_find_uri_handler2(httpd_err_resp_t *err,
struct httpd_data *hd,
const char *uri, size_t uri_len,
httpd_method_t method)
{
*err = 0;
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
if (hd->hd_calls[i]) {
ESP_LOGD(TAG, LOG_FMT("[%d] = %s"), i, hd->hd_calls[i]->uri);
if ((strlen(hd->hd_calls[i]->uri) == uri_len) && // First match uri length
(strncmp(hd->hd_calls[i]->uri, uri, uri_len) == 0)) { // Then match uri strings
if (hd->hd_calls[i]->method == method) { // Finally match methods
return hd->hd_calls[i];
}
/* URI found but method not allowed.
* If URI IS found later then this
* error is to be neglected */
*err = HTTPD_405_METHOD_NOT_ALLOWED;
}
}
free((char*)hd->hd_calls[i]->uri);
free(hd->hd_calls[i]);
hd->hd_calls[i] = NULL;
}
if (*err == 0) {
*err = HTTPD_404_NOT_FOUND;
}
return NULL;
}
esp_err_t httpd_uri(struct httpd_data *hd)
@ -189,12 +282,11 @@ esp_err_t httpd_uri(struct httpd_data *hd)
httpd_err_resp_t err = 0;
ESP_LOGD(TAG, LOG_FMT("request for %s with type %d"), req->uri, req->method);
/* URL parser result contains offset and length of path string */
if (res->field_set & (1 << UF_PATH)) {
uri = httpd_find_uri_handler2(&err, hd,
req->uri + res->field_data[UF_PATH].off,
res->field_data[UF_PATH].len,
req->method);
uri = httpd_find_uri_handler(hd, req->uri + res->field_data[UF_PATH].off,
res->field_data[UF_PATH].len, req->method, &err);
}
/* If URI with method not found, respond with error code */
@ -204,7 +296,8 @@ esp_err_t httpd_uri(struct httpd_data *hd)
ESP_LOGW(TAG, LOG_FMT("URI '%s' not found"), req->uri);
return httpd_resp_send_err(req, HTTPD_404_NOT_FOUND);
case HTTPD_405_METHOD_NOT_ALLOWED:
ESP_LOGW(TAG, LOG_FMT("Method '%d' not allowed for URI '%s'"), req->method, req->uri);
ESP_LOGW(TAG, LOG_FMT("Method '%d' not allowed for URI '%s'"),
req->method, req->uri);
return httpd_resp_send_err(req, HTTPD_405_METHOD_NOT_ALLOWED);
default:
return ESP_FAIL;

View File

@ -167,3 +167,68 @@ TEST_CASE("Basic Functionality Tests", "[HTTP SERVER]")
test_handler_limit(hd);
TEST_ASSERT(httpd_stop(hd) == ESP_OK);
}
TEST_CASE("URI Wildcard Matcher Tests", "[HTTP SERVER]")
{
struct uritest {
const char *template;
const char *uri;
bool matches;
};
struct uritest uris[] = {
{"/", "/", true},
{"", "", true},
{"/", "", false},
{"/wrong", "/", false},
{"/", "/wrong", false},
{"/asdfghjkl/qwertrtyyuiuioo", "/asdfghjkl/qwertrtyyuiuioo", true},
{"/path", "/path", true},
{"/path", "/path/", false},
{"/path/", "/path", false},
{"?", "", false}, // this is not valid, but should not crash
{"?", "sfsdf", false},
{"/path/?", "/pa", false},
{"/path/?", "/path", true},
{"/path/?", "/path/", true},
{"/path/?", "/path/alalal", false},
{"/path/*", "/path", false},
{"/path/*", "/", false},
{"/path/*", "/path/", true},
{"/path/*", "/path/blabla", true},
{"*", "", true},
{"*", "/", true},
{"*", "/aaa", true},
{"/path/?*", "/pat", false},
{"/path/?*", "/pathb", false},
{"/path/?*", "/pathxx", false},
{"/path/?*", "/pathblabla", false},
{"/path/?*", "/path", true},
{"/path/?*", "/path/", true},
{"/path/?*", "/path/blabla", true},
{"/path/*?", "/pat", false},
{"/path/*?", "/pathb", false},
{"/path/*?", "/pathxx", false},
{"/path/*?", "/path", true},
{"/path/*?", "/path/", true},
{"/path/*?", "/path/blabla", true},
{"/path/*/xxx", "/path/", false},
{"/path/*/xxx", "/path/*/xxx", true},
{}
};
struct uritest *ut = &uris[0];
while(ut->template != 0) {
bool match = httpd_uri_match_wildcard(ut->template, ut->uri, strlen(ut->uri));
TEST_ASSERT(match == ut->matches);
ut++;
}
}

View File

@ -0,0 +1,6 @@
# The following lines of boilerplate have to be in your project's CMakeLists
# in this exact order for cmake to work correctly
cmake_minimum_required(VERSION 3.5)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
project(file_server)

View File

@ -0,0 +1,9 @@
#
# This is a project Makefile. It is assumed the directory this Makefile resides in is a
# project subdirectory.
#
PROJECT_NAME := file_server
include $(IDF_PATH)/make/project.mk

View File

@ -0,0 +1,36 @@
# Simple HTTPD File Server Example
(See the README.md file in the upper level 'examples' directory for more information about examples.)
HTTP file server example demonstrates file serving using the 'esp_http_server' component of ESP-IDF:
1. URI `/path/filename` for GET command downloads the corresponding file (if exists)
2. URI `/upload` POST command for uploading the file onto the device
3. URI `/delete` POST command for deleting the file from the device
File server implementation can be found under `main/file_server.c` which uses SPIFFS for file storage. `main/upload_script.html` has some HTML, JavaScript and Ajax content used for file uploading, which is embedded in the flash image and used as it is when generating the home page of the file server.
## Usage
* Configure the project using `make menuconfig` and goto :
* Example Configuration ->
1. WIFI SSID: WIFI network to which your PC is also connected to.
2. WIFI Password: WIFI password
* In order to test the file server demo :
1. compile and burn the firmware `make flash`
2. run `make monitor` and note down the IP assigned to your ESP module. The default port is 80
3. test the example interactively on a web browser (assuming IP is 192.168.43.130):
1. open path `http://192.168.43.130/` or `http://192.168.43.130/index.html` to see an HTML web page with list of files on the server (initially empty)
2. use the file upload form on the webpage to select and upload a file to the server
3. click a file link to download / open the file on browser (if supported)
4. click the delete link visible next to each file entry to delete them
4. test the example using curl (assuming IP is 192.168.43.130):
1. `curl -X POST --data-binary @myfile.html 192.168.43.130:80/upload/path/on/device/myfile_copy.html`
* `myfile.html` is uploaded to `/path/on/device/myfile_copy.html`
2. `curl 192.168.43.130:80/path/on/device/myfile_copy.html > myfile_copy.html`
* Downloads the uploaded copy back
3. Compare the copy with the original using `cmp myfile.html myfile_copy.html`
## Note
Browsers often send large header fields when an HTML form is submit. Therefore, for the purpose of this example, 'HTTPD_MAX_REQ_HDR_LEN' has been increased to 1024 in `sdkconfig.defaults`. User can adjust this value as per their requirement, keeping in mind the memory constraint of the hardware in use.

View File

@ -0,0 +1,6 @@
set(COMPONENT_SRCS "main.c" "file_server.c")
set(COMPONENT_ADD_INCLUDEDIRS ".")
set(COMPONENT_EMBED_FILES "favicon.ico" "upload_script.html")
register_component()

View File

@ -0,0 +1,16 @@
menu "Example Configuration"
config WIFI_SSID
string "WiFi SSID"
default "myssid"
help
SSID (network name) for the example to connect to.
config WIFI_PASSWORD
string "WiFi Password"
default "mypassword"
help
WiFi password (WPA or WPA2) for the example to use.
Can be left blank if the network has no security set.
endmenu

View File

@ -0,0 +1,7 @@
#
# "main" pseudo-component makefile.
#
# (Uses default behaviour of compiling all source files in directory, adding 'include' to include path.)
COMPONENT_EMBED_FILES := favicon.ico
COMPONENT_EMBED_FILES += upload_script.html

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.3 KiB

View File

@ -0,0 +1,493 @@
/* HTTP File Server Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <string.h>
#include <sys/param.h>
#include <sys/unistd.h>
#include <sys/stat.h>
#include <dirent.h>
#include "esp_err.h"
#include "esp_log.h"
#include "esp_vfs.h"
#include "esp_spiffs.h"
#include "esp_http_server.h"
/* Max length a file path can have on storage */
#define FILE_PATH_MAX (ESP_VFS_PATH_MAX + CONFIG_SPIFFS_OBJ_NAME_LEN)
/* Max size of an individual file. Make sure this
* value is same as that set in upload_script.html */
#define MAX_FILE_SIZE (200*1024) // 200 KB
#define MAX_FILE_SIZE_STR "200KB"
/* Scratch buffer size */
#define SCRATCH_BUFSIZE 8192
struct file_server_data {
/* Base path of file storage */
char base_path[ESP_VFS_PATH_MAX + 1];
/* Scratch buffer for temporary storage during file transfer */
char scratch[SCRATCH_BUFSIZE];
};
static const char *TAG = "file_server";
/* Handler to redirect incoming GET request for /index.html to / */
static esp_err_t index_html_get_handler(httpd_req_t *req)
{
httpd_resp_set_status(req, "301 Permanent Redirect");
httpd_resp_set_hdr(req, "Location", "/");
httpd_resp_send(req, NULL, 0); // Response body can be empty
return ESP_OK;
}
/* Send HTTP response with a run-time generated html consisting of
* a list of all files and folders under the requested path */
static esp_err_t http_resp_dir_html(httpd_req_t *req)
{
char fullpath[FILE_PATH_MAX];
char entrysize[16];
const char *entrytype;
DIR *dir = NULL;
struct dirent *entry;
struct stat entry_stat;
/* Retrieve the base path of file storage to construct the full path */
strcpy(fullpath, ((struct file_server_data *)req->user_ctx)->base_path);
/* Concatenate the requested directory path */
strcat(fullpath, req->uri);
dir = opendir(fullpath);
const size_t entrypath_offset = strlen(fullpath);
if (!dir) {
/* If opening directory failed then send 404 server error */
httpd_resp_send_404(req);
return ESP_OK;
}
/* Send HTML file header */
httpd_resp_sendstr_chunk(req, "<!DOCTYPE html><html><body>");
/* Get handle to embedded file upload script */
extern const unsigned char upload_script_start[] asm("_binary_upload_script_html_start");
extern const unsigned char upload_script_end[] asm("_binary_upload_script_html_end");
const size_t upload_script_size = (upload_script_end - upload_script_start);
/* Add file upload form and script which on execution sends a POST request to /upload */
httpd_resp_send_chunk(req, (const char *)upload_script_start, upload_script_size);
/* Send file-list table definition and column labels */
httpd_resp_sendstr_chunk(req,
"<table class=\"fixed\" border=\"1\">"
"<col width=\"800px\" /><col width=\"300px\" /><col width=\"300px\" /><col width=\"100px\" />"
"<thead><tr><th>Name</th><th>Type</th><th>Size (Bytes)</th><th>Delete</th></tr></thead>"
"<tbody>");
/* Iterate over all files / folders and fetch their names and sizes */
while ((entry = readdir(dir)) != NULL) {
entrytype = (entry->d_type == DT_DIR ? "directory" : "file");
strncpy(fullpath + entrypath_offset, entry->d_name, sizeof(fullpath) - entrypath_offset);
if (stat(fullpath, &entry_stat) == -1) {
ESP_LOGE(TAG, "Failed to stat %s : %s", entrytype, entry->d_name);
continue;
}
sprintf(entrysize, "%ld", entry_stat.st_size);
ESP_LOGI(TAG, "Found %s : %s (%s bytes)", entrytype, entry->d_name, entrysize);
/* Send chunk of HTML file containing table entries with file name and size */
httpd_resp_sendstr_chunk(req, "<tr><td><a href=\"");
httpd_resp_sendstr_chunk(req, req->uri);
httpd_resp_sendstr_chunk(req, entry->d_name);
if (entry->d_type == DT_DIR) {
httpd_resp_sendstr_chunk(req, "/");
}
httpd_resp_sendstr_chunk(req, "\">");
httpd_resp_sendstr_chunk(req, entry->d_name);
httpd_resp_sendstr_chunk(req, "</a></td><td>");
httpd_resp_sendstr_chunk(req, entrytype);
httpd_resp_sendstr_chunk(req, "</td><td>");
httpd_resp_sendstr_chunk(req, entrysize);
httpd_resp_sendstr_chunk(req, "</td><td>");
httpd_resp_sendstr_chunk(req, "<form method=\"post\" action=\"/delete");
httpd_resp_sendstr_chunk(req, req->uri);
httpd_resp_sendstr_chunk(req, entry->d_name);
httpd_resp_sendstr_chunk(req, "\"><button type=\"submit\">Delete</button></form>");
httpd_resp_sendstr_chunk(req, "</td></tr>\n");
}
closedir(dir);
/* Finish the file list table */
httpd_resp_sendstr_chunk(req, "</tbody></table>");
/* Send remaining chunk of HTML file to complete it */
httpd_resp_sendstr_chunk(req, "</body></html>");
/* Send empty chunk to signal HTTP response completion */
httpd_resp_sendstr_chunk(req, NULL);
return ESP_OK;
}
#define IS_FILE_EXT(filename, ext) \
(strcasecmp(&filename[strlen(filename) - sizeof(ext) + 1], ext) == 0)
/* Set HTTP response content type according to file extension */
static esp_err_t set_content_type_from_file(httpd_req_t *req)
{
if (IS_FILE_EXT(req->uri, ".pdf")) {
return httpd_resp_set_type(req, "application/pdf");
} else if (IS_FILE_EXT(req->uri, ".html")) {
return httpd_resp_set_type(req, "text/html");
} else if (IS_FILE_EXT(req->uri, ".jpeg")) {
return httpd_resp_set_type(req, "image/jpeg");
}
/* This is a limited set only */
/* For any other type always set as plain text */
return httpd_resp_set_type(req, "text/plain");
}
/* Send HTTP response with the contents of the requested file */
static esp_err_t http_resp_file(httpd_req_t *req)
{
char filepath[FILE_PATH_MAX];
FILE *fd = NULL;
struct stat file_stat;
/* Retrieve the base path of file storage to construct the full path */
strcpy(filepath, ((struct file_server_data *)req->user_ctx)->base_path);
/* Concatenate the requested file path */
strcat(filepath, req->uri);
if (stat(filepath, &file_stat) == -1) {
ESP_LOGE(TAG, "Failed to stat file : %s", filepath);
/* If file doesn't exist respond with 404 Not Found */
httpd_resp_send_404(req);
return ESP_OK;
}
fd = fopen(filepath, "r");
if (!fd) {
ESP_LOGE(TAG, "Failed to read existing file : %s", filepath);
/* If file exists but unable to open respond with 500 Server Error */
httpd_resp_set_status(req, "500 Server Error");
httpd_resp_sendstr(req, "Failed to read existing file!");
return ESP_OK;
}
ESP_LOGI(TAG, "Sending file : %s (%ld bytes)...", filepath, file_stat.st_size);
set_content_type_from_file(req);
/* Retrieve the pointer to scratch buffer for temporary storage */
char *chunk = ((struct file_server_data *)req->user_ctx)->scratch;
size_t chunksize;
do {
/* Read file in chunks into the scratch buffer */
chunksize = fread(chunk, 1, SCRATCH_BUFSIZE, fd);
/* Send the buffer contents as HTTP response chunk */
if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK) {
fclose(fd);
ESP_LOGE(TAG, "File sending failed!");
/* Abort sending file */
httpd_resp_sendstr_chunk(req, NULL);
/* Send error message with status code */
httpd_resp_set_status(req, "500 Server Error");
httpd_resp_sendstr(req, "Failed to send file!");
return ESP_OK;
}
/* Keep looping till the whole file is sent */
} while (chunksize != 0);
/* Close file after sending complete */
fclose(fd);
ESP_LOGI(TAG, "File sending complete");
/* Respond with an empty chunk to signal HTTP response completion */
httpd_resp_send_chunk(req, NULL, 0);
return ESP_OK;
}
/* Handler to download a file kept on the server */
static esp_err_t download_get_handler(httpd_req_t *req)
{
// Check if the target is a directory
if (req->uri[strlen(req->uri) - 1] == '/') {
// In so, send an html with directory listing
http_resp_dir_html(req);
} else {
// Else send the file
http_resp_file(req);
}
return ESP_OK;
}
/* Handler to upload a file onto the server */
static esp_err_t upload_post_handler(httpd_req_t *req)
{
char filepath[FILE_PATH_MAX];
FILE *fd = NULL;
struct stat file_stat;
/* Skip leading "/upload" from URI to get filename */
/* Note sizeof() counts NULL termination hence the -1 */
const char *filename = req->uri + sizeof("/upload") - 1;
/* Filename cannot be empty or have a trailing '/' */
if (strlen(filename) == 0 || filename[strlen(filename) - 1] == '/') {
ESP_LOGE(TAG, "Invalid file name : %s", filename);
/* Respond with 400 Bad Request */
httpd_resp_set_status(req, "400 Bad Request");
/* Send failure reason */
httpd_resp_sendstr(req, "Invalid file name!");
return ESP_OK;
}
/* Retrieve the base path of file storage to construct the full path */
strcpy(filepath, ((struct file_server_data *)req->user_ctx)->base_path);
/* Concatenate the requested file path */
strcat(filepath, filename);
if (stat(filepath, &file_stat) == 0) {
ESP_LOGE(TAG, "File already exists : %s", filepath);
/* If file exists respond with 400 Bad Request */
httpd_resp_set_status(req, "400 Bad Request");
httpd_resp_sendstr(req, "File already exists!");
return ESP_OK;
}
/* File cannot be larger than a limit */
if (req->content_len > MAX_FILE_SIZE) {
ESP_LOGE(TAG, "File too large : %d bytes", req->content_len);
httpd_resp_set_status(req, "400 Bad Request");
httpd_resp_sendstr(req, "File size must be less than "
MAX_FILE_SIZE_STR "!");
/* Return failure to close underlying connection else the
* incoming file content will keep the socket busy */
return ESP_FAIL;
}
fd = fopen(filepath, "w");
if (!fd) {
ESP_LOGE(TAG, "Failed to create file : %s", filepath);
/* If file creation failed, respond with 500 Server Error */
httpd_resp_set_status(req, "500 Server Error");
httpd_resp_sendstr(req, "Failed to create file!");
return ESP_OK;
}
ESP_LOGI(TAG, "Receiving file : %s...", filename);
/* Retrieve the pointer to scratch buffer for temporary storage */
char *buf = ((struct file_server_data *)req->user_ctx)->scratch;
int received;
/* Content length of the request gives
* the size of the file being uploaded */
int remaining = req->content_len;
while (remaining > 0) {
ESP_LOGI(TAG, "Remaining size : %d", remaining);
/* Receive the file part by part into a buffer */
if ((received = httpd_req_recv(req, buf, MIN(remaining, SCRATCH_BUFSIZE))) <= 0) {
if (received == HTTPD_SOCK_ERR_TIMEOUT) {
/* Retry if timeout occurred */
continue;
}
/* In case of unrecoverable error,
* close and delete the unfinished file*/
fclose(fd);
unlink(filepath);
ESP_LOGE(TAG, "File reception failed!");
/* Return failure reason with status code */
httpd_resp_set_status(req, "500 Server Error");
httpd_resp_sendstr(req, "Failed to receive file!");
return ESP_OK;
}
/* Write buffer content to file on storage */
if (received && (received != fwrite(buf, 1, received, fd))) {
/* Couldn't write everything to file!
* Storage may be full? */
fclose(fd);
unlink(filepath);
ESP_LOGE(TAG, "File write failed!");
httpd_resp_set_status(req, "500 Server Error");
httpd_resp_sendstr(req, "Failed to write file to storage!");
return ESP_OK;
}
/* Keep track of remaining size of
* the file left to be uploaded */
remaining -= received;
}
/* Close file upon upload completion */
fclose(fd);
ESP_LOGI(TAG, "File reception complete");
/* Redirect onto root to see the updated file list */
httpd_resp_set_status(req, "303 See Other");
httpd_resp_set_hdr(req, "Location", "/");
httpd_resp_sendstr(req, "File uploaded successfully");
return ESP_OK;
}
/* Handler to delete a file from the server */
static esp_err_t delete_post_handler(httpd_req_t *req)
{
char filepath[FILE_PATH_MAX];
struct stat file_stat;
/* Skip leading "/upload" from URI to get filename */
/* Note sizeof() counts NULL termination hence the -1 */
const char *filename = req->uri + sizeof("/upload") - 1;
/* Filename cannot be empty or have a trailing '/' */
if (strlen(filename) == 0 || filename[strlen(filename) - 1] == '/') {
ESP_LOGE(TAG, "Invalid file name : %s", filename);
/* Respond with 400 Bad Request */
httpd_resp_set_status(req, "400 Bad Request");
/* Send failure reason */
httpd_resp_sendstr(req, "Invalid file name!");
return ESP_OK;
}
/* Retrieve the base path of file storage to construct the full path */
strcpy(filepath, ((struct file_server_data *)req->user_ctx)->base_path);
/* Concatenate the requested file path */
strcat(filepath, filename);
if (stat(filepath, &file_stat) == -1) {
ESP_LOGE(TAG, "File does not exist : %s", filename);
/* If file does not exist respond with 400 Bad Request */
httpd_resp_set_status(req, "400 Bad Request");
httpd_resp_sendstr(req, "File does not exist!");
return ESP_OK;
}
ESP_LOGI(TAG, "Deleting file : %s", filename);
/* Delete file */
unlink(filepath);
/* Redirect onto root to see the updated file list */
httpd_resp_set_status(req, "303 See Other");
httpd_resp_set_hdr(req, "Location", "/");
httpd_resp_sendstr(req, "File deleted successfully");
return ESP_OK;
}
/* Handler to respond with an icon file embedded in flash.
* Browsers expect to GET website icon at URI /favicon.ico */
static esp_err_t favicon_get_handler(httpd_req_t *req)
{
extern const unsigned char favicon_ico_start[] asm("_binary_favicon_ico_start");
extern const unsigned char favicon_ico_end[] asm("_binary_favicon_ico_end");
const size_t favicon_ico_size = (favicon_ico_end - favicon_ico_start);
httpd_resp_set_type(req, "image/x-icon");
httpd_resp_send(req, (const char *)favicon_ico_start, favicon_ico_size);
return ESP_OK;
}
/* Function to start the file server */
esp_err_t start_file_server(const char *base_path)
{
static struct file_server_data *server_data = NULL;
/* Validate file storage base path */
if (!base_path || strcmp(base_path, "/spiffs") != 0) {
ESP_LOGE(TAG, "File server presently supports only '/spiffs' as base path");
return ESP_ERR_INVALID_ARG;
}
if (server_data) {
ESP_LOGE(TAG, "File server already started");
return ESP_ERR_INVALID_STATE;
}
/* Allocate memory for server data */
server_data = calloc(1, sizeof(struct file_server_data));
if (!server_data) {
ESP_LOGE(TAG, "Failed to allocate memory for server data");
return ESP_ERR_NO_MEM;
}
strlcpy(server_data->base_path, base_path,
sizeof(server_data->base_path));
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
/* Use the URI wildcard matching function in order to
* allow the same handler to respond to multiple different
* target URIs which match the wildcard scheme */
config.uri_match_fn = httpd_uri_match_wildcard;
ESP_LOGI(TAG, "Starting HTTP Server");
if (httpd_start(&server, &config) != ESP_OK) {
ESP_LOGE(TAG, "Failed to start file server!");
return ESP_FAIL;
}
/* Register handler for index.html which should redirect to / */
httpd_uri_t index_html = {
.uri = "/index.html",
.method = HTTP_GET,
.handler = index_html_get_handler,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &index_html);
/* Handler for URI used by browsers to get website icon */
httpd_uri_t favicon_ico = {
.uri = "/favicon.ico",
.method = HTTP_GET,
.handler = favicon_get_handler,
.user_ctx = NULL
};
httpd_register_uri_handler(server, &favicon_ico);
/* URI handler for getting uploaded files */
httpd_uri_t file_download = {
.uri = "/*", // Match all URIs of type /path/to/file (except index.html)
.method = HTTP_GET,
.handler = download_get_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_download);
/* URI handler for uploading files to server */
httpd_uri_t file_upload = {
.uri = "/upload/*", // Match all URIs of type /upload/path/to/file
.method = HTTP_POST,
.handler = upload_post_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_upload);
/* URI handler for deleting files from server */
httpd_uri_t file_delete = {
.uri = "/delete/*", // Match all URIs of type /delete/path/to/file
.method = HTTP_POST,
.handler = delete_post_handler,
.user_ctx = server_data // Pass server data as context
};
httpd_register_uri_handler(server, &file_delete);
return ESP_OK;
}

View File

@ -0,0 +1,127 @@
/* HTTP File Server Example
This example code is in the Public Domain (or CC0 licensed, at your option.)
Unless required by applicable law or agreed to in writing, this
software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
CONDITIONS OF ANY KIND, either express or implied.
*/
#include <sys/param.h>
#include "esp_wifi.h"
#include "esp_event_loop.h"
#include "esp_log.h"
#include "esp_system.h"
#include "esp_spiffs.h"
#include "nvs_flash.h"
/* This example demonstrates how to create file server
* using esp_http_server. This file has only startup code.
* Look in file_server.c for the implementation */
/* The example uses simple WiFi configuration that you can set via
* 'make menuconfig'.
* If you'd rather not, just change the below entries to strings
* with the config you want -
* ie. #define EXAMPLE_WIFI_SSID "mywifissid"
*/
#define EXAMPLE_WIFI_SSID CONFIG_WIFI_SSID
#define EXAMPLE_WIFI_PASS CONFIG_WIFI_PASSWORD
static const char *TAG="example";
/* Wi-Fi event handler */
static esp_err_t event_handler(void *ctx, system_event_t *event)
{
switch(event->event_id) {
case SYSTEM_EVENT_STA_START:
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_START");
ESP_ERROR_CHECK(esp_wifi_connect());
break;
case SYSTEM_EVENT_STA_GOT_IP:
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_GOT_IP");
ESP_LOGI(TAG, "Got IP: '%s'",
ip4addr_ntoa(&event->event_info.got_ip.ip_info.ip));
break;
case SYSTEM_EVENT_STA_DISCONNECTED:
ESP_LOGI(TAG, "SYSTEM_EVENT_STA_DISCONNECTED");
ESP_ERROR_CHECK(esp_wifi_connect());
break;
default:
break;
}
return ESP_OK;
}
/* Function to initialize Wi-Fi at station */
static void initialise_wifi(void)
{
ESP_ERROR_CHECK(nvs_flash_init());
tcpip_adapter_init();
ESP_ERROR_CHECK(esp_event_loop_init(event_handler, NULL));
wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
ESP_ERROR_CHECK(esp_wifi_init(&cfg));
ESP_ERROR_CHECK(esp_wifi_set_storage(WIFI_STORAGE_RAM));
wifi_config_t wifi_config = {
.sta = {
.ssid = EXAMPLE_WIFI_SSID,
.password = EXAMPLE_WIFI_PASS,
},
};
ESP_LOGI(TAG, "Setting WiFi configuration SSID %s...", wifi_config.sta.ssid);
ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA));
ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config));
ESP_ERROR_CHECK(esp_wifi_start());
}
/* Function to initialize SPIFFS */
static esp_err_t init_spiffs(void)
{
ESP_LOGI(TAG, "Initializing SPIFFS");
esp_vfs_spiffs_conf_t conf = {
.base_path = "/spiffs",
.partition_label = NULL,
.max_files = 5, // This decides the maximum number of files that can be created on the storage
.format_if_mount_failed = true
};
esp_err_t ret = esp_vfs_spiffs_register(&conf);
if (ret != ESP_OK) {
if (ret == ESP_FAIL) {
ESP_LOGE(TAG, "Failed to mount or format filesystem");
} else if (ret == ESP_ERR_NOT_FOUND) {
ESP_LOGE(TAG, "Failed to find SPIFFS partition");
} else {
ESP_LOGE(TAG, "Failed to initialize SPIFFS (%s)", esp_err_to_name(ret));
}
return ESP_FAIL;
}
size_t total = 0, used = 0;
ret = esp_spiffs_info(NULL, &total, &used);
if (ret != ESP_OK) {
ESP_LOGE(TAG, "Failed to get SPIFFS partition information (%s)", esp_err_to_name(ret));
return ESP_FAIL;
}
ESP_LOGI(TAG, "Partition size: total: %d, used: %d", total, used);
return ESP_OK;
}
/* Declare the function which starts the file server.
* Implementation of this function is to be found in
* file_server.c */
esp_err_t start_file_server(const char *base_path);
void app_main()
{
initialise_wifi();
/* Initialize file storage */
ESP_ERROR_CHECK(init_spiffs());
/* Start the file server */
ESP_ERROR_CHECK(start_file_server("/spiffs"));
}

View File

@ -0,0 +1,80 @@
<table class="fixed" border="0">
<col width="1000px" /><col width="500px" />
<tr><td>
<h2>ESP32 File Server</h2>
</td><td>
<table border="0">
<tr>
<td>
<label for="newfile">Upload a file</label>
</td>
<td colspan="2">
<input id="newfile" type="file" onchange="setpath()" style="width:100%;">
</td>
</tr>
<tr>
<td>
<label for="filepath">Set path on server</label>
</td>
<td>
<input id="filepath" type="text" style="width:100%;">
</td>
<td>
<button id="upload" type="button" onclick="upload()">Upload</button>
</td>
</tr>
</table>
</td></tr>
</table>
<script>
function setpath() {
var default_path = document.getElementById("newfile").files[0].name;
document.getElementById("filepath").value = default_path;
}
function upload() {
var filePath = document.getElementById("filepath").value;
var upload_path = "/upload/" + filePath;
var fileInput = document.getElementById("newfile").files;
/* Max size of an individual file. Make sure this
* value is same as that set in file_server.c */
var MAX_FILE_SIZE = 200*1024;
var MAX_FILE_SIZE_STR = "200KB";
if (fileInput.length == 0) {
alert("No file selected!");
} else if (filePath.length == 0) {
alert("File path on server is not set!");
} else if (filePath.indexOf(' ') >= 0) {
alert("File path on server cannot have spaces!");
} else if (filePath[filePath.length-1] == '/') {
alert("File name not specified after path!");
} else if (fileInput[0].size > 200*1024) {
alert("File size must be less than 200KB!");
} else {
document.getElementById("newfile").disabled = true;
document.getElementById("filepath").disabled = true;
document.getElementById("upload").disabled = true;
var file = fileInput[0];
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4) {
if (xhttp.status == 200) {
document.open();
document.write(xhttp.responseText);
document.close();
} else if (xhttp.status == 0) {
alert("Server closed the connection abruptly!");
location.reload()
} else {
alert(xhttp.status + " Error!\n" + xhttp.responseText);
location.reload()
}
}
};
xhttp.open("POST", upload_path, true);
xhttp.send(file);
}
}
</script>

View File

@ -0,0 +1,6 @@
# Name, Type, SubType, Offset, Size, Flags
# Note: if you change the phy_init or app partition offset, make sure to change the offset in Kconfig.projbuild
nvs, data, nvs, 0x9000, 0x6000,
phy_init, data, phy, 0xf000, 0x1000,
factory, app, factory, 0x10000, 1M,
storage, data, spiffs, , 0xF0000,
1 # Name, Type, SubType, Offset, Size, Flags
2 # Note: if you change the phy_init or app partition offset, make sure to change the offset in Kconfig.projbuild
3 nvs, data, nvs, 0x9000, 0x6000,
4 phy_init, data, phy, 0xf000, 0x1000,
5 factory, app, factory, 0x10000, 1M,
6 storage, data, spiffs, , 0xF0000,

View File

@ -0,0 +1,6 @@
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions_example.csv"
CONFIG_PARTITION_TABLE_CUSTOM_APP_BIN_OFFSET=0x10000
CONFIG_PARTITION_TABLE_FILENAME="partitions_example.csv"
CONFIG_APP_OFFSET=0x10000
CONFIG_HTTPD_MAX_REQ_HDR_LEN=1024