生成用于在WordPress中存储图像的POST请求

时间:2015-05-19 10:27:04

标签: php wordpress image-upload

我正在使用WordPress将图像保存到其媒体库中。图像以base64格式发送,因此我想知道在解码后我们如何为该base64图像发出POST数据请求,因为WordPress的wp_handle_upload函数不通过url接受图像。

这是我的代码

$image = $_REQUEST['image'];  // requested image
include('../wp-load.php');  // Load wordpress engine
include_once('config.php');
$data = base64_decode($image);   // decode image
$filename = "IMG_".time().".png";  // filename 
//$fileurl = "../wp-content/uploads".$directory.$filename;
//file_put_contents($fileurl, $data);
// wordpress wp_handle_upload not accept image via url 
if ( ! function_exists( 'wp_handle_upload' ) ) require_once( ABSPATH . 'wp-admin/includes/file.php' );
$uploadedfile = $data;
$upload_overrides = array( 'test_form' => false );
$movefile = wp_handle_upload( $uploadedfile, $upload_overrides );
if ( $movefile ) {
    // echo "file loaded";
}
if ( $movefile ) {
    $wp_filetype = $movefile['type'];
    $filename = $movefile['file'];
    $wp_upload_dir = wp_upload_dir();
    $attachment = array(
        'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
        'post_mime_type' => $wp_filetype,
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
        'post_content' => '',
        'post_status' => 'inherit'
    );
    $attach_id = wp_insert_attachment( $attachment, $filename);
}

1 个答案:

答案 0 :(得分:4)

我用另一种方式,我将解码后的base64图像写入uploads文件夹,然后将其作为附件插入

$postId = $_REQUEST['postId'];
$image = $_REQUEST['image'];
$directory = "/".date(Y)."/".date(m)."/";
$wp_upload_dir = wp_upload_dir();
$data = base64_decode($image);
$filename = "IMG_".time().".png";
//$fileurl = $wp_upload_dir['url'] . '/' . basename( $filename );
$fileurl = "../wp-content/uploads".$directory.$filename;

$filetype = wp_check_filetype( basename( $fileurl), null );

file_put_contents($fileurl, $data);

    $attachment = array(
        'guid' => $wp_upload_dir['url'] . '/' . basename( $fileurl ),
        'post_mime_type' => $filetype['type'],
        'post_title' => preg_replace('/\.[^.]+$/', '', basename($fileurl)),
        'post_content' => '',
        'post_status' => 'inherit'
    );
//  print_r($attachment);
//echo "<br>file name :  $fileurl";
    $attach_id = wp_insert_attachment( $attachment, $fileurl ,$postId);
require_once('../wp-admin/includes/image.php' );

// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $fileurl );
wp_update_attachment_metadata( $attach_id, $attach_data );

希望它会帮助某人:)