From 72d166a05070b62bfb34472cde057b5673dccc52 Mon Sep 17 00:00:00 2001 From: cgfhtw Date: Tue, 20 Feb 2024 08:38:29 +0100 Subject: [PATCH] FHCAPI Controller: multipart upload --- application/core/FHCAPI_Controller.php | 4 +++ public/js/plugin/FhcApi.js | 39 ++++++++++++++++++++++++++ 2 files changed, 43 insertions(+) diff --git a/application/core/FHCAPI_Controller.php b/application/core/FHCAPI_Controller.php index 3bc5c7280..e59740ded 100644 --- a/application/core/FHCAPI_Controller.php +++ b/application/core/FHCAPI_Controller.php @@ -89,6 +89,10 @@ class FHCAPI_Controller extends FHC_Controller // For JSON Requests (as opposed to multipart/form-data) get the $_POST variable from the input stream instead if ($this->input->get_request_header('Content-Type', true) == 'application/json') $_POST = json_decode($this->security->xss_clean($this->input->raw_input_stream), true); + elseif (isset($_POST['_jsondata'])) { + $_POST = array_merge($_POST, json_decode($_POST['_jsondata'], true)); + unset($_POST['_jsondata']); + } } diff --git a/public/js/plugin/FhcApi.js b/public/js/plugin/FhcApi.js index 335dec45e..bacd27d43 100644 --- a/public/js/plugin/FhcApi.js +++ b/public/js/plugin/FhcApi.js @@ -52,6 +52,45 @@ export default { baseURL: FHC_JS_DATA_STORAGE_OBJECT.app_root + FHC_JS_DATA_STORAGE_OBJECT.ci_router + "/" }); + fhcApiAxios.interceptors.request.use(config => { + if (config.method != 'post' || !config.data) + return config; + + if (config.data instanceof FormData) + return config; + + if (!Object.values(config.data).every(item => { + if (item instanceof FileList) + return false; + if (Array.isArray(item)) + return item.every(i => !(i instanceof File)); + return true; + })) { + const newData = Object.entries(config.data).reduce((nd, [key, item]) => { + if (item instanceof FileList) { + for (const file of item) + nd.FormData.append(key + (item.length > 1 ? '[]' : ''), file); + } else if (Array.isArray(item)) { + if (item.every(i => !(i instanceof File))) { + nd.jsondata[key] = item; + } else { + item.forEach(file => nd.FormData.append(key + (item.length > 1 ? '[]' : ''), file)); + } + } else { + nd.jsondata[key] = item; + } + return nd; + }, { + FormData: new FormData(), + jsondata: {} + }); + newData.FormData.append('_jsondata', JSON.stringify(newData.jsondata)); + config.data = newData.FormData; + } + + return config; + }); + fhcApiAxios.interceptors.response.use(response => { if (response.config?.errorHandling == 'off' || response.config?.errorHandling === false