Как разместить бинарный файл в Файловой службе API Dreamfactory
В Dreamfactory (v2.4.2) я публикую (через multipart/form-data) сервис /_table/{tablename}, чтобы создать запись в таблице. Используя PHP, я затем использую идентификатор этой записи, возвращенный в качестве имени папки для хранения файлов. Я хотел бы, чтобы сценарий service/_table/{tablename}.post_process отправлялся с использованием метода platform.api.post и передавал ему двоичные данные из исходного запроса, но мне трудно определить, как передавать эти данные без base64_encoding это.
Как передать запрос multipart / form-data из исходного запроса события во внутренний вызов API другого сервиса? Заранее спасибо за помощь!
1 ответ
С тех пор я нашел решение. Пожалуйста, предоставьте любые советы или рекомендации по улучшению, я довольно новичок, но потратил последние 2 дня на изучение и устранение неисправностей. У меня есть следующие настройки:
НА КЛИЕНТА:
URL сообщения: /tableService/_table/tableName
Почтовые данные: Форма метода: multipart/form-data
-Вы должны предоставить каждое из полей таблицы в виде key:value
pair
-Вы должны предоставить файл загрузки с ключом "files
"-Тебе также нужны ваши заголовки аутентификации (X-DreamFactory-Session-Token
& X-Dreamfactory-API-Key
)
НА СЕРВЕРЕ:
Вам нужно будет настроить сценарий до и после обработки для таблицы.
... PRE_PROCE SS
tableService._table.tableName.post.pre_process
if(!isset($_FILES['files']) || !is_array($_FILES['files'])){
// Stop execution and return a specific status code
$event['response']['errorCode'] = 400;
$event['response']['errorMessage'] = "File is missing. Check that the a file was provided and the field name is: [files], to continue.";
return false;
} else {
$event['payload'] = $_POST;
// use this next variable if your table has a field, "fileName" to store the file name. This should be changed to your needs
$event['payload']['fileName'] = $_FILES['files']['name'];
$event['payload'] = array("resource"=>array($event['payload']));
$event['request']['payload'] = $event['payload'];
$event['request']['content'] = json_encode($event['payload']);
$event['request']['content_type'] = 'json';
}
Отсюда, таблица должна добавить запись, мы будем обрабатывать загрузку файла в post_process
скрипт для таблицы.
... post_process
tableService._table.tableName.post.post_process
// we need to get the ID of the created record. Be sure to use the variable you want to use as your ID.
$recordId = $r['primaryKeyId'];
// For path, you can prepend an already existing directory if you need to like this.
$path = '/Documents/'.$recordId;
// The filename should be in the returned resource, assuming you store it. Otherwise, you can pull this from the $_FILES array, if you haven't changed it from the POST'd value. We should only have one file, so we'll use resource 0.
$filename = $event['payload']['resource'][0]['fileName'];
/**
* Prepping file for upload via API Endpoint
*/
// This is the URL for your internal files API Endpoint
$url = 'fileService/'.$path;
// let's create the directory, we need to make sure there is a trailing slash
$post($url.'/');
// we need to read the file data into a string, so we'll use file_get_contents on the tmp file.
$fileData = file_get_contents($_FILES['files']['tmp_name']);
$post($url.'/'.$filename, $fileData);