When submitting form data via jQuery and using admin-ajax, including a file attachment was easy:
var data = new FormData($(this)[0]);
How do you include a file attachment when submitting form data to a Rest Controller?
This submits all the form fields, except the file attachment.
var data = $this.serializeArray();
The jQuery:
$('#create-book-form').submit(function (e) {
var $this = $(this);
e.preventDefault();
//var data = new FormData($(this)[0]);
var data = $this.serializeArray();
data.push({name: "rtype", value: "create"});
$.ajax({
url: BOOK_SUBMITTER.root + 'rfp-books/v1/books',
data: $.param(data),
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', BOOK_SUBMITTER.nonce );
},
//etc
It all works, except the file is not part of the form data that arrives at the rest controller. Yes, I have an input called 'file' so the user can include a jpg.
I need to send all the form data in a single call.
The post attachment is created right after the post is created in the controller.
So, how do I get the file into the data included in $.param(data)
In the route callback in the REST Controller:
$params = $request->get_params();
write_log( $params );
The log shows all the form data - except the file. ( If I submit the jQuery data as FormData, none of the data is recognized in the controller. )