通过 JSON:API,我在 Drupal 9.5.8 上创建和更新内容实体——对于内容、分类、关系,它工作正常。
但我无法上传图片 - 它们似乎已损坏。 我试过这种脚本:https://www.drupal.org/project/drupal/issues/3079384#comment-13250753
import requests
import os
from requests.auth import HTTPBasicAuth
def upload_image(image_path):
api_url = 'https://example.com/jsonapi/node/event/a8ef729b-1fd6-4233-979a-fa0f81132dde/field_image' #?_format=json
auth = HTTPBasicAuth('Username', 'Password')
image_filename = os.path.basename(image_path)
headers = {'Content-Type': 'application/octet-stream',
'Content-Disposition': 'file; filename="{}"'.format(image_filename.replace('images/', ''))}
multipart_form_data = {'file': (image_filename, open(image_path, 'rb'))}
print(api_url)
print(auth)
print(image_filename)
print(headers)
response = requests.post(api_url, files=multipart_form_data, headers=headers, auth=auth)
print(response.json())
return None
upload_image('images/test.jpg')
我已经尝试并错误地使用了一些其他/类似的方法,例如:
def upload_image2(image_path):
api_url = 'https://example.com/jsonapi/node/event/a8ef729b-1fd6-4233-979a-fa0f81132dde/field_image' #?_format=json
auth = HTTPBasicAuth('Username', 'Password')
image_filename = os.path.basename(image_path)
headers = {'Accept': 'application/vnd.api+json',
'Content-Type': 'application/octet-stream',
'Content-Disposition': f'file; filename="{image_filename}"'
}
with open('images/test.jpg', 'rb') as f:
response = requests.post(api_url, headers=headers, auth=auth, files={'test.jpg': f})
print(response.json())
return None
很奇怪:将
#?_format=json
添加到 upload_image2 不会改变任何东西。但是将它添加到upload_image,我收到一个错误:
{'message': '找不到指定格式 json 的路由。支持的格式:api_json.'}
上传的图片是 11.3 kB - 我不能在这里上传,因为它看起来是一张破损的图片。
According to that comment, I'm not trying to base64 encode the image.
有一个 CURL 和 Node.js 示例 - 但我无法将它转移到 Python,就像它看起来的那样。
在这张票中,似乎也可以使用 BasicAuth 来上传文件,所以这也可能不是问题。
我做错了什么?
经过多次摆弄,我能够通过以下代码使其工作:https://www.drupal.org/node/3024331#comment-13248319
好像是
data = bytearray(data)
是丢失的一块。
对于文件上传,请查看此 Drupal.org Post 这可以通过 Postman 完成。
上传的图片是临时的,您需要在某处引用它才能使其永久保存。