使用Python向Drupal 9.5.8上传图片时文件损坏问题求助
Drupal 9.5.8 JSON:API 图片上传后损坏问题
问题描述
在Drupal 9.5.8上通过JSON:API创建、更新内容实体时,内容编辑、分类关联等操作均正常,但图片上传后显示损坏。
上传前图片大小为11.1 kB,上传后变为11.3 kB,无法正常显示,网站编辑表单中直接显示图片损坏状态。
已尝试的代码
方案1
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')
方案2
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
异常现象
- 给方案1的URL添加
#?_format=json时会报错:
{'message': 'No route found for the specified format json. Supported formats: api_json.'}
- 给方案2的URL添加该参数无影响。
已确认的信息
- 未对图片进行base64编码,符合官方工单说明;
- BasicAuth可正常用于文件上传,认证环节无问题;
- 官方提供了CURL和Node.js的上传示例,但无法转换为可用的Python代码。
请问我的操作哪里出错了?
内容的提问来源于stack exchange,提问作者Chris
相关产品推荐
相关产品推荐

