gpt4 book ai didi

wordpress - WP Rest API 上传图片

转载 作者:行者123 更新时间:2023-12-03 14:46:25 25 4
gpt4 key购买 nike

我正在尝试通过 Wordpress REST api v2 上传图片。到目前为止,我所做的只是在 wordpress 媒体库中创建空条目。这意味着它们有图像名称,但没有实际图像。

发布请求:

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

回复:
{
"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"
}
]
}
}

我没有收到任何错误,似乎一切正常,除了响应-> 发表 和响应-> 媒体详情 为 null 或为空。当然图像本身不会上传。

基于此 GitHub WP-API Adding Media票,我应该发送 2 个请求。先 POST请求应返回带有 post 对象的数据。我会通过 PUT 发送这个帖子对象方法,并且应该上传图像......因为我没有帖子对象,这是不可能的。

任何想法我做错了什么?

最佳答案

对于任何寻找 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);
});

关于wordpress - WP Rest API 上传图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37432114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com