因此,為了觸及問題的核心,我想在帶有api (v2)的 worpress 站點上發布影像。
問題的第一部分是我沒有 url 或檔案路徑,我只有從之前完成的匯出中獲得的變數中的影像的原始資料。
問題的第二部分是一旦發布(正常情況下),影像在管理員的媒體庫中顯示為空白。
這是我的代碼:
if (isset($product['priority_web_image'])) {
$image_name = $product['priority_web_image']['filename'];
$data = $product['priority_web_image']['data'];
$ext = substr($image_name, strpos($image_name, ".") 1);
if ($ext == 'jpg') {
$ext = 'jpeg';
}
$mime_type = 'image/'.$ext;
$headers = [
'Authorization' => 'Bearer '.$result_auth->access_token,
"cache-control" => "no-cache",
"Content-Type" => $mime_type,
"Content-Disposition" => "attachement;filename=".$image_name,
];
$body = [
"source_url" => $data,
"slug" => "image_test_pimcore",
"status" => "future",
"title" => $image_name,
"media_type" => "image",
"mime_type" => $mime_type
];
$options = [
"headers" => $headers,
"form_params" => $body,
];
$result = $this->WPApi->request("POST", "media", $options);
$bodyAry = json_decode($result->getBody());
//echo print_r($bodyAry);
return $bodyAry;
}
我使用 Guzzle 來提出請求。
如果有人知道我錯過了什么,我會接受:-)。
uj5u.com熱心網友回復:
我找到了解決方案!
file_put_contents($filepath, base64_decode($data));
// Make sure the image exist
if (!file_exists($filepath)){return;}
// Load the image
$file = file_get_contents($filepath);
// Get the filename
$filename = $image_name? $image_name : basename($filepath);
// Initiate curl.
$ch = curl_init();
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt( $ch, CURLOPT_URL, $url .'/wp-json/wp/v2/media/' );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
"Content-Disposition: form-data; filename=\"$filename\"",
'Authorization: Bearer ' .$result_auth->access_token,
] );
$result = curl_exec( $ch );
curl_close( $ch );
// Decode the response
$api_response = json_decode($result);
return $api_response;
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/389439.html
標籤:php 图片 邮政 命令 wordpress-rest-api
上一篇:Pygame中閃爍的精靈
