Python 无法将图像二进制文件添加到多部分/表单数据中

Python 无法将图像二进制文件添加到多部分/表单数据中,python,python-3.x,multipartform-data,Python,Python 3.x,Multipartform Data,我收到一个错误:应为str实例,在我尝试将图像二进制添加到多部分/表单数据时找到字节 问题是我试图将二进制格式的imageData附加到字符串中。有没有办法将二进制图像添加到多部分/表单数据中 我束手无策,希望能得到一些帮助 imageData = request.FILES['filePath'].read() content_type, request_body = encode_multipart_formdata([('include_target_data', targetMeta

我收到一个错误:应为str实例,在我尝试将图像二进制添加到多部分/表单数据时找到字节

问题是我试图将二进制格式的imageData附加到字符串中。有没有办法将二进制图像添加到多部分/表单数据中

我束手无策,希望能得到一些帮助

imageData = request.FILES['filePath'].read()


content_type, request_body = encode_multipart_formdata([('include_target_data', targetMetaDataRet),
                                                     ('max_num_results', str(maxNoResultRet))],
                                                     [('image', imagePath, imageData)])

def encode_multipart_formdata(fields, files):

    BOUNDARY = '----------ThIs_Is_tHe_bouNdaRY_$'
    CRLF = '\r\n'
    lines = []
    for (key, value) in fields:
        lines.append('--' + BOUNDARY)
        lines.append('Content-Disposition: form-data; name="%s"' % key)
        lines.append('')
        lines.append(value)
    for (key, filename, value) in files:
        lines.append('--' + BOUNDARY)
        lines.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        lines.append('Content-Type: %s' % get_content_type(filename))
        lines.append('')
        lines.append(value)
    lines.append('--' + BOUNDARY + '--')
    lines.append('')
    body = CRLF.join(lines)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body
回溯:

  35.            response = get_response(request)

  128.           response = self.process_exception_by_middleware(e, request)

  126.           response = wrapped_callback(request, *callback_args, **callback_kwargs)

  166.           [('image', imagePath, imageData)])

  232.           body = CRLF.join(lines)

Exception Type: TypeError at /identify_shrine
Exception Value: sequence item 12: expected str instance, bytes found
content_type = 'multipart/form-data; boundary=----------ThIs_Is_tHe_bouNdaRY_$'
request_body = '----------ThIs_Is_tHe_bouNdaRY_$' +  '\n'+'Content-Disposition: form-data; name="include_target_data"' + '\n' + '\n' + 'top'+ '\n' + '----------ThIs_Is_tHe_bouNdaRY_$' +'\n' + 'Content-Disposition: form-data; name="max_num_results"' + '\n' + '\n' + '1' + '\n' + '----------ThIs_Is_tHe_bouNdaRY_$' +'\n' + 'Content-Disposition: form-data; name="image"; filename="img_2.jpg"' + '\n' + 'Content-Type: image/jpeg' + '\n' + '\n'
request_body1 = request_body.encode('utf-8')
request_body2 = imageData
request_body3 = ('\n' + '\n' + '----------ThIs_Is_tHe_bouNdaRY_$').encode('utf-8')
request_body4 = request_body1 + request_body2 + request_body3

content_type_bare = 'multipart/form-data'

# Sign the request and get the Authorization header
# use client key
auth_header = authorization_header_for_request(CLIENT_ACCESS_KEY, CLIENT_SECRET_KEY, HTTP_METHOD, request_body4,
                                               content_type_bare,
                                               date, path)

request_headers = {
    'Accept': 'application/json',
    'Authorization': auth_header,
    'Content-Type': content_type,
    'Date': date
}
try:
    # Make the request over HTTPS on port 443
    connection = http.client.HTTPSConnection(CLOUD_RECO_API_ENDPOINT, 443)
    connection.request(HTTP_METHOD, path, request_body4, request_headers)

    response = connection.getresponse()
    response_body = response.read()
    reason = response.reason
    status = response.status

finally:
    connection.close()
根据@coltoneakins请求,我将请求正文修改为字节,但我似乎收到了一个错误的请求,知道为什么吗?

代码:

  35.            response = get_response(request)

  128.           response = self.process_exception_by_middleware(e, request)

  126.           response = wrapped_callback(request, *callback_args, **callback_kwargs)

  166.           [('image', imagePath, imageData)])

  232.           body = CRLF.join(lines)

Exception Type: TypeError at /identify_shrine
Exception Value: sequence item 12: expected str instance, bytes found
content_type = 'multipart/form-data; boundary=----------ThIs_Is_tHe_bouNdaRY_$'
request_body = '----------ThIs_Is_tHe_bouNdaRY_$' +  '\n'+'Content-Disposition: form-data; name="include_target_data"' + '\n' + '\n' + 'top'+ '\n' + '----------ThIs_Is_tHe_bouNdaRY_$' +'\n' + 'Content-Disposition: form-data; name="max_num_results"' + '\n' + '\n' + '1' + '\n' + '----------ThIs_Is_tHe_bouNdaRY_$' +'\n' + 'Content-Disposition: form-data; name="image"; filename="img_2.jpg"' + '\n' + 'Content-Type: image/jpeg' + '\n' + '\n'
request_body1 = request_body.encode('utf-8')
request_body2 = imageData
request_body3 = ('\n' + '\n' + '----------ThIs_Is_tHe_bouNdaRY_$').encode('utf-8')
request_body4 = request_body1 + request_body2 + request_body3

content_type_bare = 'multipart/form-data'

# Sign the request and get the Authorization header
# use client key
auth_header = authorization_header_for_request(CLIENT_ACCESS_KEY, CLIENT_SECRET_KEY, HTTP_METHOD, request_body4,
                                               content_type_bare,
                                               date, path)

request_headers = {
    'Accept': 'application/json',
    'Authorization': auth_header,
    'Content-Type': content_type,
    'Date': date
}
try:
    # Make the request over HTTPS on port 443
    connection = http.client.HTTPSConnection(CLOUD_RECO_API_ENDPOINT, 443)
    connection.request(HTTP_METHOD, path, request_body4, request_headers)

    response = connection.getresponse()
    response_body = response.read()
    reason = response.reason
    status = response.status

finally:
    connection.close()

代码中存在类型问题。您将获得一个TypeError预期的str实例,找到的字节数,因为您正在尝试join()一个包含Python中str类型和bytes类型的列表

请查看代码中的以下行:

用于文件中的(键、文件名、值):
行。追加('--'+边界)
line.append('Content-Disposition:表单数据;name=“%s”;filename=“%s””%(键,文件名))
line.append('内容类型:%s'%get\u内容类型(文件名))
行。追加(“”)

lines.append(value)#你能用有问题的行发布错误回溯吗?@SamuelDion Girardeau谢谢你的回复,添加了回溯:-)注意:你可以使用
请求
库来完成这项任务,这将为你进行多部分编码,从而让你的生活变得更加轻松。否则,您可以使用
email.mime
包(标准库的一部分)对多部分/表单数据输出进行ecode。如果我将整个请求正文转换为字节,请求标题和接受、授权、日期是否也需要以字节为单位?您好,我对代码进行了更改,需要您的帮助,谢谢!好问题。简短的回答是否定的。例如,请求库不这样做。此外,如果您在Firefox等web浏览器中使用“网络”面板,您可以看到当您将文件上传到图像共享站点时,请求是如何形成的。处理头文件时,头文件不是二进制数据。但是,身体是。如果您想了解更多有关如何工作的信息,请阅读UTF-8字符编码和二进制。您好,我愚蠢地创建了请求头字节,对文本进行了更改,但仍然收到一个错误的请求,知道吗?请参阅:。另外,我不认为您是在以CRLF结尾--“\n”与“\r\n”不同。为了更好地排除错误,我们应该查看代码正在形成的请求体。然后,将其与多部分/表单请求正文的正确格式进行比较。另见: