wordpress WP Rest API 上传图片
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37432114/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
WP Rest API upload image
提问by CrazySabbath
I'm trying to upload image via Wordpress REST api v2. So far all I managed was to create empty entries in wordpress media library. Meaning they have image names, but no actual image.
我正在尝试通过 Wordpress REST api v2 上传图像。到目前为止,我所做的只是在 wordpress 媒体库中创建空条目。这意味着它们有图像名称,但没有实际图像。
POST Request:
POST请求:
http://localhost/wordpress/wp-json/wp/v2/media
Authorization: Basic d29yZHByZXNzOndvcmRwcmVzcw==
Content-Type: application/json
Content-Disposition: attachment;filename=map2.jpg
{
"source_url" : "file:///C:/Users/x/Desktop/map2.jpg"
}
Response:
回复:
{
"id": 127,
"date": "2016-05-25T08:43:30",
"date_gmt": "2016-05-25T08:43:30",
"guid": {
"rendered": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg",
"raw": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg"
},
"modified": "2016-05-25T08:43:30",
"modified_gmt": "2016-05-25T08:43:30",
"password": "",
"slug": "map2-3",
"status": "inherit",
"type": "attachment",
"link": "http://localhost/wordpress/map2-3/",
"title": {
"raw": "map2-3",
"rendered": "map2-3"
},
"author": 1,
"comment_status": "open",
"ping_status": "closed",
"alt_text": "",
"caption": "",
"description": "",
"media_type": "image",
"mime_type": "image/jpeg",
"media_details": {},
"post": null,
"source_url": "http://localhost/wordpress/wp-content/uploads/2016/05/map2-3.jpg",
"_links": {
"self": [
{
"href": "http://localhost/wordpress/wp-json/wp/v2/media/127"
}
],
"collection": [
{
"href": "http://localhost/wordpress/wp-json/wp/v2/media"
}
],
"about": [
{
"href": "http://localhost/wordpress/wp-json/wp/v2/types/attachment"
}
],
"author": [
{
"embeddable": true,
"href": "http://localhost/wordpress/wp-json/wp/v2/users/1"
}
],
"replies": [
{
"embeddable": true,
"href": "http://localhost/wordpress/wp-json/wp/v2/comments?post=127"
}
]
}
}
I get no errors, everything's seem to be working, except response->postand response->media_detailsis either null or empty. Ofcourse image itself is not uploaded.
我没有收到任何错误,一切似乎都在工作,除了 response-> post和 response-> media_details为 null 或为空。当然图片本身没有上传。
Based on this GitHub WP-API Adding Mediaticket, I should send 2 requests. First POST
request should return data with post object. I would send this post object via PUT
method, and image should be uploaded...since I have no post object, this is not possible.
基于此GitHub WP-API 添加媒体票证,我应该发送 2 个请求。第一个POST
请求应该返回带有 post 对象的数据。我会通过PUT
方法发送这个帖子对象,并且应该上传图像......因为我没有帖子对象,这是不可能的。
Any ideas what am I doing wrong?
任何想法我做错了什么?
回答by rtrigoso
Sideloading images is not supported by the wordpress api so you will have to do some changes.
wordpress api 不支持旁加载图像,因此您必须进行一些更改。
First, your content-typeshould be image/jpegand not application/json, remember that content-type is supposed to reflect the data that you are passing and the POST media request expects an image.
首先,你的content-type应该是image/jpeg而不是application/json,记住 content-type 应该反映你传递的数据,POST 媒体请求需要一个图像。
Another change you have to make to accommodate the content-type is the way that you are passing the data. Instead of sending it with the source_url parameter, try passing it as a binary file.
为适应内容类型而必须进行的另一个更改是传递数据的方式。不要使用 source_url 参数发送它,而是尝试将其作为二进制文件传递。
One last thing I would mention is that the wp/v2 calls return 3XX status on a few occasions. It would be useful to follow those redirects and redo those requests to those new urls.
我要提到的最后一件事是 wp/v2 调用有时会返回 3XX 状态。跟踪这些重定向并将这些请求重做到这些新 url 会很有用。
I had some issues passing JPEG images but PNG images have worked well. Here is a curl example that I use to upload png media:
我在传递 JPEG 图像时遇到了一些问题,但 PNG 图像运行良好。这是我用来上传 png 媒体的 curl 示例:
curl --request POST \
--url http://www.yoursite.com/wp-json/wp/v2/media \
--header "cache-control: no-cache" \
--header "content-disposition: attachment; filename=tmp" \
--header "authorization: Basic d29yZHByZXNzOndvcmRwcmVzcw==" \
--header "content-type: image/png" \
--data-binary "@/home/web/tmp.png" \
--location
回答by Ayman Magedy
My working answer using PHP cUrl
我使用 PHP cUrl 的工作答案
<?php
$curl = curl_init();
$data = file_get_contents('C:\test.png');
curl_setopt_array($curl, array(
CURLOPT_URL => "http://woo.dev/wp-json/wp/v2/media",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_HTTPHEADER => array(
"authorization: Basic XxxxxxxXxxxxXx=",
"cache-control: no-cache",
"content-disposition: attachment; filename=test.png",
"content-type: image/png",
),
CURLOPT_POSTFIELDS => $data,
));
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}
回答by Matthias Dorn
After trying to get the image upload running with wp_remote_post (don′t wanna use curl for several reasons) i came up with the following working solution:
在尝试使用 wp_remote_post 运行图像上传后(出于多种原因不想使用 curl),我想出了以下工作解决方案:
// Upload image to wordpress media library
$file = @fopen( 'image.jpg', 'r' );
$file_size = filesize( 'image.jpg' );
$file_data = fread( $file, $file_size );
$args = array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( 'USERNAME:PASSWORD' ),
'accept' => 'application/json', // The API returns JSON
'content-type' => 'application/binary', // Set content type to binary
'Content-Disposition' => 'attachment; filename=nameoffileonserver.jpg'
),
'body' => $file_data
);
$api_response = wp_remote_post( 'http://myserver.com/wp-json/wp/v2/media', $args);
回答by Yoandy Pérez Villazón
At january 2020 using wordpress 5.3.2 with nginx the solution that work for me is:
2020 年 1 月,在 nginx 中使用 wordpress 5.3.2 对我有用的解决方案是:
function uploadFile($token, $archivo) {
$file = file_get_contents( $archivo );
$mime = mime_content_type( $archivo );
$url = BASEAPI. 'wp-json/wp/v2/media';
$ch = curl_init();
curl_setopt( $ch, CURLOPT_URL, $url );
curl_setopt( $ch, CURLOPT_POST, 1 );
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt( $ch, CURLOPT_POSTFIELDS, $file );
curl_setopt($ch, CURLOPT_BINARYTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt( $ch, CURLOPT_HTTPHEADER, [
'Content-Type: '.$mime,
'Content-Disposition: attachment; filename="'.basename($archivo).'"',
'Authorization: Bearer ' .$token,
] );
$result = curl_exec( $ch );
curl_close( $ch );
print_r( json_decode( $result ) );
}
The token is the Authorization JWT token and $archivo is the path to file.
令牌是授权 JWT 令牌,$archivo 是文件的路径。
回答by Alipio Gabriel
Here you can use this code snippet. This works for me using Wordpress API REST
您可以在这里使用此代码片段。这对我使用 Wordpress API REST 有效
<?php
//Add this to your function.php
function upload_image( $imageID, $login ) {
$request_url = 'https://DOMAINNAME.com/wp-json/wp/v2/media'; //change the domainname
$image_file_path = get_attached_file($imageID); //change this to your file meda path if your not throwing media file to other server
$image = file_get_contents( $image_file_path );
$mime = mime_content_type( $image_file_path );
$api_media_response = wp_remote_post( $request_url, array(
'headers' => array(
'Authorization' => 'Basic ' . base64_encode( $login ), //login format USERNAME:PASSWORD
'Content-Disposition' => 'attachment; filename='.basename($image_file_path).'',
'Content-Type' => $mime
),
'body' => $image
) );
//this function return wp_remote_post
// more info => https://developer.wordpress.org/reference/functions/wp_remote_post/
}
回答by Uli Krause
For anyone looking for a JS solution, here's how I made it work using Axios. I will skip authorization implementations, as there are a few options around (oAuth, JWT, Basic).
对于任何正在寻找 JS 解决方案的人,以下是我使用 Axios 使其工作的方式。我将跳过授权实现,因为有几个选项(oAuth、JWT、Basic)。
const fs = require('fs');
const axios = require('axios');
axios({
url: 'http(s)://{your-wp-domain}/wp-json/wp/v2/media',
method: 'POST',
headers: {
'Content-Disposition':'attachment; filename="file.jpg"',
Authorization: {your-authorization-method},
'Content-Type':'image/jpeg'
},
data: fs.readFileSync('path/to/file.jpg', (err, data) => {
if (err) {
console.log(err);
}
});
})
.then(res => {
console.log(res.data);
})
.catch(err => {
console.log(err);
});