为每个单个输入参数发送不同的 'Content-Type' 一个文件和其他数据参数

sending different 'Content-Type' for each single input param one file and other data params

有什么方法可以为每个输入参数 multipart-form 发送每个不同的 'Content-Type' 数据

例如

Content-Type: multipart/form-data;boundary=q235Ht2tTWJhuFmC8sJxbQ7YGU7FwQafcZd8B
Accept-Charset: utf-8
"Content-Disposition: form-data; name="creative_id"
"Content-Type: text/plain;charset=ISO-8859-1”
…
"Content-Disposition: form-data; name=“file_role""
"Content-Type: text/plain;charset=ISO-8859-1”
…
"Content-Disposition: form-data; name="Filename""
"Content-Type: text/plain;charset=ISO-8859-1
"Content-Disposition: form-data; name="file"; filename="advertise_A.png"
"Content-Type: image/x-png"

对于整个请求,header 将是 Content-Type: multipart/form-data; 但是对于像 creative_id 和 file_role 这样的参数, 我想发送 Content-Type: text/plain;charset=ISO-8859-1 对于文件本身 Content-Type:image/x-png

我尝试了两种方法,但没有用:

headers = {'Content-Type':'text/plain;charset=ISO-8859-1'} 
files = {'file': open(asset_file, 'rb')}
and then in POST (url, files=files, headers=headers, params=values)

files = {'file1': (open(asset_file, 'rb'), 'image/x-png'), 'creative_id': (1727968, 'text/plain;charset=ISO-8859-1'), 'file_role': ('PRIMARY', 'text/plain;charset=ISO-8859-1')}
and then in POST (url, files=files)

您与第二个示例非常接近。如果您提供一个以元组作为其值的字典,则元组具有以下形式:

(filename, file object or content, [content type], [headers])

其中 content typeheaders 字段是可选的。

这意味着您想这样做:

files = {'file': ('advertise_A.png', open(asset_file, 'rb'), 'image/x-png'), 'creative_id': ('', '1727968', 'text/plain;charset=ISO-8859-1'), 'file_role': ('', 'PRIMARY', 'text/plain;charset=ISO-8859-1'), 'Filename': ('', 'advertise_A.png', 'text/plain;charset=ISO-8859-1')}
r = requests.post(url, files=files)

对仅包含字符串 basic_test 的文件执行上述操作,我得到以下结果:

Content-Type: multipart/form-data; boundary=82c444831d6a450ba5c4ced2e1cc7866

--82c444831d6a450ba5c4ced2e1cc7866
Content-Disposition: form-data; name="creative_id"
Content-Type: text/plain;charset=ISO-8859-1

1727968
--82c444831d6a450ba5c4ced2e1cc7866
Content-Disposition: form-data; name="file_role"
Content-Type: text/plain;charset=ISO-8859-1

PRIMARY
--82c444831d6a450ba5c4ced2e1cc7866
Content-Disposition: form-data; name="file"; filename="advertise_A.png"
Content-Type: image/x-png

basic_test
--82c444831d6a450ba5c4ced2e1cc7866
Content-Disposition: form-data; name="Filename"
Content-Type: text/plain;charset=ISO-8859-1

advertise_A.png
--82c444831d6a450ba5c4ced2e1cc7866--