图像显示为空白图像

时间:2019-05-22 作者:wplearner

我正在尝试通过API将base 64编码的图像上载到我的网站媒体库。API返回图像ID,但这些图像在我的媒体库中显示为空白图像。这是我的密码

add_action(\'rest_api_init\', function () {
register_rest_route( \'api/v1\', \'upload_image/\',array(
      \'methods\'  => \'POST\',
      \'callback\' => \'accept_image\'
 ));
});

function accept_image($request){
$parameters = $request->get_query_params();
$parameters = $parameters[\'image\'];

$decoded = base64_decode(str_replace(\'data:image/png;base64,\',\'\',$parameters));
$upload_dir = wp_upload_dir();
$upload_path = str_replace( \'/\', DIRECTORY_SEPARATOR, $upload_dir[\'path\'] ) . DIRECTORY_SEPARATOR;
$filename = \'my_image.png\';
$hashed_filename = md5( $filename . microtime() ) . \'_\' . $filename;
$image_upload = file_put_contents( $upload_path . $hashed_filename, $decoded );

//HANDLE UPLOADED FILE
if( !function_exists( \'wp_handle_sideload\' ) ) {
  require_once( ABSPATH . \'wp-admin/includes/file.php\' );
}

// Without that I\'m getting a debug error!?
if( !function_exists( \'wp_get_current_user\' ) ) {
  require_once( ABSPATH . \'wp-includes/pluggable.php\' );
}

// @new
$file             = array();
$file[\'error\']    = \'\';
$file[\'tmp_name\'] = $upload_path . $hashed_filename;
$file[\'name\']     = $hashed_filename;
$file[\'type\']     = \'image/png\';
$file[\'size\']     = filesize( $upload_path . $hashed_filename );

// upload file to server
// @new use $file instead of $image_upload
$file_return = wp_handle_sideload( $file, array( \'test_form\' => false ) );

$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 );

return $attach_id;
}
我想知道我的问题在哪里,以及如何解决这个问题。我将非常感谢你的帮助。

2 个回复
最合适的回答,由SO网友:wplearner 整理而成

这个功能最终对我起了作用。

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;
}

SO网友:Sally CJ

您应该生成附件元数据,如宽度和高度—以及创建附件后的文件路径和缩略图:

使用wp_generate_attachment_metadata():

$attach_id = wp_insert_attachment( $attachment, $filename );

if ( $attach_id ) {
    require_once ABSPATH . \'wp-admin/includes/image.php\';
    $metadata = wp_generate_attachment_metadata( $attach_id, $filename );
    wp_update_attachment_metadata( $attach_id, $metadata );
}
<使用wp_maybe_generate_attachment_metadata():
$attach_id = wp_insert_attachment( $attachment, $filename );

if ( $attachment = get_post( $attach_id ) ) {
    require_once ABSPATH . \'wp-admin/includes/image.php\';
    wp_maybe_generate_attachment_metadata( $attachment );
}
您可以使用media_handle_sideload() 而不是wp_handle_sideload() 创建附件(及其元数据)。所以你可以用它来代替你现在所拥有的// upload file to serverreturn $attach_id;:

// upload file to server
require_once ABSPATH . \'wp-admin/includes/media.php\';
require_once ABSPATH . \'wp-admin/includes/image.php\';
$attach_id = media_handle_sideload( $file, 0 );

return $attach_id;

相关推荐

WP REST API-如果查询没有帖子,如何获得空响应

我正在使用rest_{post_type}_query 对于某些自定义查询参数。它工作得很好,但是,当查询没有要匹配的帖子ID时,我希望得到一个空响应或一条“找不到帖子”消息。目前它得到了所有的帖子。function query_video_by_politician($args, $request) { if(isset($request[\"politician_id\"]) && intval($request[\"politician_id\"])) { &