Hi all. I'm absolutely stumped and can't seem to find a solution to this.
Basically, I'm sending a POST request from outside of my wordpress installation '/wp-admin/admin-ajax.php' to send an image to Wordpress and save it as an attachment to one of my posts.
To do this I have converted the image to a Base64 string on the client side using Javascript, sending that as part of the POST request, decoding that on the server side as part of my script, moving the file to my uploads directory and then attaching the file to a post/adding it to the media library.
I can do this quite simply using the $_FILES function (a normal upload) but Base64 is required because I need to be able to submit images from all sorts of different applications.
My code looks like this...
Step 1 -
//Collect Base64 and convert to file
$upload_dir = wp_upload_dir();
$decoded = base64_decode($_POST['base64File']);
$filename = 'newImage.jpg';
$hashed_filename = MD5($filename . microtime()) . '_' . $filename;
$image_upload = file_put_contents($upload_dir['path'] . '\/' . $hashed_filename, $decoded);
//HANDLE UPLOADED FILE
if (!function_exists('wp_handle_sideload')) require_once(ABSPATH . 'wp-admin/includes/file.php');
//upload file to server
$file_return = wp_handle_sideload($image_upload, array('test_form' => false));
//return error if there is one
if(isset($file_return['error']) || isset($file_return['upload_error_handler'])) {
$jsonReturn = array(
'error' => 'Error uploading.',
'code' => '95234'
);
} else {
/**
* See http://codex.wordpress.org/Function_Reference/wp_insert_attachment
*/
$filename = $file_return['file'];
$attachment = array(
'post_mime_type' => $file_return['type'],
'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
'post_content' => '',
'post_status' => 'inherit',
'guid' => $wp_upload_dir['url'] . '/' . basename($filename)
);
$attach_id = wp_insert_attachment( $attachment, $filename, 289 );
// you must first include the image.php file
// for the function wp_generate_attachment_metadata() to work
require_once(ABSPATH . 'wp-admin/includes/image.php');
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
$jsonReturn = array(
'Status' => 'Success'
);
}
Basically what I am struggling to do is get '$image_upload' to conform to the first required parameter for
wp_handle_sideload($image_upload, array('test_form' => false));
as it says there are no file contents when it tries to execute.
Is there anyone with any idea/experience of dealing with Base64 strings/files???