这个功能最终对我起了作用。
function accept_image($request){
error_reporting(E_ALL);
//Image should be set as the body of the POST request, as a base-64 encoded string.
//It should NOT include decorations such as data:image/png;base64, at the beginning. It should only be the encoded file itself.
//Everything else should be sent via the header
$is_valid = false;
header(\'Content-Type: application/json\', true);
$response = array(\'success\'=> $is_valid, \'message\' => \'\');
$image = $request->get_body();
$decoded_file = base64_decode($image, true);
if(strlen($image) == 0 || $decoded_file === false){
return api_msg(false, \'An error occurred during base64_decode().\');
}
$content_type = $request->get_header("Content-Type");
$ext = \'\';
switch($content_type){
case "image/jpg":
case "image/jpeg":
$ext = "jpg";
break;
case "image/png";
$ext = "png";
break;
default:
return api_msg(false, "Invalid Content-Type in request header. Acceptable formats are \'image/jpg\' or \'image/png\'.");
break;
}
$upload_dir = wp_upload_dir();
$upload_path = str_replace( \'/\', DIRECTORY_SEPARATOR, $upload_dir[\'path\'] ) . DIRECTORY_SEPARATOR;
$rand = md5( rand(3,10) . microtime() );
$hashed_filename = "api_upload_{$rand}.{$ext}";
$image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded_file );
if($image_upload === false)
return api_msg(false, "An error occurred during file_put_contents().");
$url_path = $upload_dir[\'url\'] . \'/\' . $hashed_filename;
$abs_path = $upload_path . $hashed_filename;
$attachment = array(
\'post_mime_type\' => $content_type,
\'post_title\' => "API Upload - " . date(\'y-m-d H:i:s\', time()),
\'post_content\' => \'\',
\'post_status\' => \'inherit\',
\'guid\' => $url_path,
);
$attach_id = wp_insert_attachment( $attachment, $abs_path );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . \'wp-admin/includes/image.php\' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $abs_path );
wp_update_attachment_metadata( $attach_id, $attach_data );
return api_msg(true, "Image Saved", $attach_id, $url_path);
}
function api_msg($is_valid, $message, $id = null, $url = null){
$resp = array(
\'success\' => $is_valid,
\'message\' => $message
);
if(!empty($id))
$resp[\'id\'] = $id;
if(!empty($url))
$resp[\'url\'] = $url;
return $resp;
}