Presently there is no out of the box support for file sharing, though it is something desirable and will be made available in future. Till then, implementing a simple file server should not be difficult. Take for this as an example :
Code: Select all
/* HTTP GET handler for downloading files */
esp_err_t file_get_handler(httpd_req_t *req)
{
/* Assuming that the sdcard has been initialized (formatted to FAT) and loaded with some files.
* Refer to sd_card_example to to know how to initialize the sd card */
const char *filepath_prefix = "/sdcard/";
char *filename = NULL;
size_t filename_len = httpd_req_get_url_query_len(req);
if (filename_len == 0) {
const char * resp_str = "Please specify a filename. eg. file?somefile.txt";
httpd_resp_send(req, resp_str, strlen(resp_str));
return ESP_OK;
}
filename = malloc(strlen(filepath_prefix) + filename_len + 1); // extra 1 byte for null termination
strncpy(filename, filepath_prefix, strlen(filepath_prefix));
// Get null terminated filename
httpd_req_get_url_query_str(req, filename + strlen(filepath_prefix), filename_len + 1);
ESP_LOGI(TAG, "Reading file : %s", filename + strlen(filepath_prefix));
FILE *f = fopen(filename, "r");
free(filename);
if (f == NULL) {
const char * resp_str = "File doesn't exist";
httpd_resp_send(req, resp_str, strlen(resp_str));
return ESP_OK;
}
/* Read file in chunks (relaxes any constraint due to large file sizes)
* and send HTTP response in chunked encoding */
char chunk[1024];
size_t chunksize;
do {
chunksize = fread(chunk, 1, sizeof(chunk), f);
if (httpd_resp_send_chunk(req, chunk, chunksize) != ESP_OK) {
fclose(f);
return ESP_FAIL;
}
} while (chunksize != 0);
httpd_resp_send_chunk(req, NULL, 0);
fclose(f);
return ESP_OK;
}
httpd_handle_t start_file_server(void)
{
httpd_handle_t server = NULL;
httpd_config_t config = HTTPD_DEFAULT_CONFIG();
httpd_uri_t file_serve = {
.uri = "/file",
.method = HTTP_GET,
.handler = file_get_handler,
.user_ctx = NULL
};
// Start the httpd server
ESP_LOGI(TAG, "Starting server on port: %d", config.server_port);
if (httpd_start(&server, &config) == ESP_OK) {
// Set URI handlers
ESP_LOGI(TAG, "Registering URI handlers");
httpd_register_uri_handler(server, &file_serve);
return server;
}
ESP_LOGI(TAG, "Error starting server!");
return NULL;
}
So in order to download a file one can run something like this :
Code: Select all
curl http://10.0.0.152:80/file?music/song.mp3 > song.mp3
Assuming "10.0.0.152" is the IP assigned to ESP32, and there is a file "music/song.mp3" in the FAT formatted sdcard.