WordPress REST API:无法上传内容类型图像/jpeg

问题描述 投票:0回答:2

WordPress REST API 显然不允许我上传内容类型为“image/jpeg”的文件。

如果我将 content-type 设置为空字符串,我就可以创建媒体项目并上传附加文件(该文件出现在媒体库和 wp_content/uploads 目录中)。然而,这样做会导致 WordPress 无法处理无效图像。

这是我正在使用的代码:

def post():
    url = 'https://www.example.com/wp-json/wp/v2/media'
    data = open('C:\\Pictures\\foo.jpg', 'rb').read()
    r = requests.post(url=url,
                    files={'filename1': data},
                    data={'title': 'Files test'},
                    headers={'Content-Type': '', 'Content-Disposition': 'attachment; filename={}'.format('foo.jpg')},
                    auth=('username', 'password'))
    return (r.status_code, r.text)

当我将 Content-Type 设置为“image/jpg”、“image/jpeg”、“image”、“multipart”、“application”或“application/image”时(我快绝望了),我得到了 403。

如果我按照其他人的建议将其设置为“application/json”,则会收到“传递了无效的 JSON 正文”的 400。

如果我省略 Content-Type,我会收到 500 并显示以下消息:

{"code":"rest_upload_unknown_error","message":"File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.","data": {"status":500}}')

我的文件不为空(它是 26kB),如果我能够上传 Content-Type = '' 的文件,则建议的 PHP.ini 错误可能不适用。

请问有什么建议吗?

python wordpress rest api python-requests
2个回答
1
投票

好的,我有一个解决方法可以正确上传图像(只需上传数据而不是文件):

def post():
    url = 'https://www.example.com/wp-json/wp/v2/media'
    data = open('C:\\Pictures\\foo.jpg', 'rb').read()
    r = requests.post(url=url,
                    data=data,
                    headers={'Content-Type': '', 'Content-Disposition': 'attachment; filename={}'.format('foo.jpg')},
                    auth=('username', 'password'))
    return (r.status_code, r.text)

请注意,Content-Type 仍设置为“”,但不知何故现在它可以工作了。


0
投票

我也曾被这个问题困扰过,最后我找到了另一种解决方案。也可以通过 multipard/form-data 发送数据(如您最初的意图)。在这种情况下,不要添加标头。这是它的样子:

formData = { 'file' : (  'foo.jpg' , open('.\foo.jpg','rb'), 'image/jpg' ) }
r = requests.post(url,auth=(username,password), files = formData)
© www.soinside.com 2019 - 2024. All rights reserved.