From 5ef29fc9dca3dafee5162a1e82ec5f6bc8446a67 Mon Sep 17 00:00:00 2001 From: helintongh Date: Tue, 5 Sep 2023 15:42:47 +0800 Subject: [PATCH] feat: can display all files, including subdirectories --- include/cinatra/http_server.hpp | 41 ++++++++++++++++++++++++--------- 1 file changed, 30 insertions(+), 11 deletions(-) diff --git a/include/cinatra/http_server.hpp b/include/cinatra/http_server.hpp index 35b50429..35c524e9 100644 --- a/include/cinatra/http_server.hpp +++ b/include/cinatra/http_server.hpp @@ -601,6 +601,29 @@ class http_server_ : private noncopyable { } } + int get_static_dir_filenames(const std::string &dir, + std::vector &filenames, + size_t dir_name_length) { + fs::path path(dir); + if (!fs::exists(path)) + return -1; + fs::directory_iterator end_iter; + for (fs::directory_iterator iter(path); iter != end_iter; ++iter) { + if (fs::is_directory(iter->status())) { + get_static_dir_filenames(iter->path().string(), filenames, + dir_name_length); + } + else { + auto u8_path_name = iter->path().u8string(); + std::string relative_path(u8_path_name.begin(), u8_path_name.end()); + size_t length = relative_path.length(); + relative_path = relative_path.substr(dir_name_length + 1, length); + filenames.push_back(relative_path); + } + } + return filenames.size(); + } + bool build_http_download_lists_response(request &req, std::string &&resp_str) { std::string res_str = ""; @@ -608,17 +631,13 @@ class http_server_ : private noncopyable { std::string(req.get_header_value("host")) + "/"; std::string href_of_tail = "\"target=\"_blank\">"; if (req.get_res_path() == download_display_file_dir_) { - std::string file_dir_str = static_dir_; - std::filesystem::path dir_path(file_dir_str); - - for (const auto &entry : std::filesystem::directory_iterator(dir_path)) { - if (!entry.is_directory()) { - auto u8_file_name = entry.path().filename().u8string(); - std::string file_name_str(u8_file_name.begin(), u8_file_name.end()); - std::string full_href = href_of_head + file_name_str + href_of_tail + - file_name_str + "
"; - res_str += full_href; - } + std::vector files; + size_t static_dir_length = static_dir_.length(); + get_static_dir_filenames(static_dir_, files, static_dir_length); + for (const auto &file : files) { + std::string full_href = + href_of_head + file + href_of_tail + file + "
"; + res_str += full_href; } std::string ret = download_dir_response_head_ + res_str + download_dir_response_tail_;