問題描述

我需要您的幫助,通過 Wp-rest-api v2 和 Oauth2 認證在我的 wordpress 博客上上傳媒體圖像。

我沒有在 REST API 文檔中找到發送我的圖像數據 (字段名稱,發送模式…?) 的方式。

require('OAuth2/Client.php');
require('OAuth2/GrantType/IGrantType.php');
require('OAuth2/GrantType/AuthorizationCode.php');

const CLIENT_ID     = 'XXX';
const CLIENT_SECRET = 'XX';

const REDIRECT_URI           = 'http://127.0.0.1/test_api_wp/test.php';

const AUTHORIZATION_ENDPOINT = 'http://wordpress.local/oauth/authorize';
const TOKEN_ENDPOINT         = 'http://wordpress.local/oauth/token';

$client = new OAuth2Client(CLIENT_ID, CLIENT_SECRET);

if (!isset($_GET['code']))
{
    $auth_url = $client->getAuthenticationUrl(AUTHORIZATION_ENDPOINT, REDIRECT_URI);
    header('Location: ' . $auth_url);
    die('Redirect');
}
else
{
    $params = array('code' => $_GET['code'], 'redirect_uri' => REDIRECT_URI);
    $response = $client->getAccessToken(TOKEN_ENDPOINT, 'authorization_code', $params); //authorization_code
    $token = $response['result']['access_token'];
    $client->setAccessToken($token);
    $client->setAccessTokenType(OAuth2Client::ACCESS_TOKEN_BEARER);

}

$values = array(
    "date" => "2015-11-26 10:00:00",
    "date_gmt" => "2015-11-26 09:00:00",
    "modified" => "2015-11-26 10:00:00",
    "modified_gmt" => "2015-11-26 09:00:00",
    "status" => "future",
    "title" => "Titre media",
    "description" => "description media",
    "media_type" => "image",
    "source_url" => "https://www.base64-image.de/build/img/mr-base64-482fa1f767.png"
);

$data = $client->fetch("wordpress.local/wp-json/wp/v2/media", $values, "POST");
echo "<pre>";print_r($data);echo "</pre>";

響應 :

Array
(
    [result] => Array
        (
            [code] => rest_upload_no_data
            [message] => No data supplied
            [data] => Array
                (
                    [status] => 400
                )

        )

    [code] => 400
    [content_type] => application/json; charset=UTF-8
)

任何想法?非常感謝

最佳解決方案

所以!這個很有趣。

請記住,WP-API 還是非常非常非常 work-in-progress 。

Content-Disposition

我發現 an issue reported on the WP-API issue queue 關於 Content-Disposition 。這是發佈新媒體內容所需的標題,而在以正確格式提供這些內容時,有一些非常非常嚴格的要求。

創建媒體端點的目的

首先,讓我們退一步。該 API 假定您已經將新文件上傳到正確的目錄。此端點正在數據庫中創建引用此文件的媒體內容。

解決方案

您必須指定要與新內容關聯的媒體文件的文件名。這不能是遠程 URL 。從 v2 documentation 可以看出,source_urllink 是 read-only 。所有您要做的成功提交您的新內容,請將以下內容添加到標題中:

'Content-Disposition' => 'filename=name-of-file.jpg',

如票中所述,您不能添加引號或指定您用於發送文件的方法。它必須是上面的格式。至少,直到他們改變它才是這種情況。

為了紀錄,當我終於想到這一個出來的時候,我笑了起來,嚇得我的妻子感到害怕。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。