I’m learning Flutter application development and I have been faced with a major issue of how to save multiple files uploaded from Pone to the WordPress website through rest API. I have been able to capture the files through Flutter as shown by the following code.
void saveCheckIn() async {
if (_image.length > 6) {
Toasts.show("Upload a max of 6 IMAGES");
return;
}
final formData = FormData.fromMap({
'name': 'dio',
'date': DateTime.now().toIso8601String(),
});
for (var imageFile in _image) {
formData.files.addAll([
MapEntry("images[]", await MultipartFile.fromFile(imageFile.path)),
]);
}
Dio dio = Dio();
dynamic headers = {
"Accept": "application/json",
"Content-type": "application/json"
};
try {
BuildContext showDialogContext = Toasts.showLoading(context: context);
var response = await dio.post(
"${Constants.baseUrl}/clients/checkin",
options: Options(
headers: headers,
),
);
Navigator.of(showDialogContext).pop();
print(response.data.toString());
} catch (e) {
Toasts.show("Error: $e");
}
}
From the above dart code, _image
is a List containing all the image files
I’m not sure how to receive those images through WordPress REST API. I have tried to do research but I can’t find anything helpful. This is my WordPress Code
add_action( 'rest_api_init', 'wpmam_rest_user_endpoints' );
function wpmam_rest_user_endpoints( $request ){
register_rest_route(
'wp-mobile-app-manager/v2',
"clients/checkin",
array(
"methods" => array( "POST", "GET", "PUT", "DELETE", "PATCH" ),
"callback" => "wpmam_mobile_app_checkin_clients"
)
);
}
function wpmam_mobile_app_checkin_clients($request){
$response = array();
$parameters = $request->get_json_params();
$username = $parameters['username'];
$password = $parameters['password'];
$name = $parameters['name'];
$date = $parameters['date'];
$images = $parameters['files']['images']; // NOT SURE IF THIS IS CORRECT
foreach ($images as $key => $value) {
// NOT SURE HOW TO MOVE ON
}
wpmap_upload_files( $request = null, $user_id = 0 );
return new WP_REST_Response( $response, 123 );
}