欢迎访问宙启技术站
智能推送

Python中的encode_multipart_formdata()函数实现文件上传示例

发布时间:2023-12-28 22:43:57

在Python中,可以使用encode_multipart_formdata()函数实现文件上传。这个函数可以将文件和其他表单数据编码为multipart/form-data格式,以便在HTTP请求中进行文件上传。

下面是一个示例的实现文件上传的函数encode_multipart_formdata()

def encode_multipart_formdata(fields, files):
    boundary = "----WebKitFormBoundary7MA4YWxkTrZu0gW"
    body = []
    
    for key, value in fields.items():
        body.append('--' + boundary)
        body.append('Content-Disposition: form-data; name="%s"\r
' % key)
        body.append(value if isinstance(value, str) else str(value))
    
    for key, file in files.items():
        filename = file['filename']
        filedata = file['data']
        mimetype = file['mimetype']
        
        body.append('--' + boundary)
        body.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        body.append('Content-Type: %s\r
' % mimetype)
        body.append(filedata)
    
    body.append('--' + boundary + '--\r
')
        
    content_type = 'multipart/form-data; boundary=%s' % boundary
    body_str = '\r
'.join(body)
    
    return content_type, body_str

函数encode_multipart_formdata()接受两个参数fieldsfiles,其中fields为包含其他表单数据的字典,files为包含要上传文件的字典。files字典中的每个键值对表示一个文件,其中键为字段名,值为一个包含文件名、文件数据和文件类型的字典。

下面是一个使用示例:

import requests

def upload_file(url, fields, files):
    content_type, body_str = encode_multipart_formdata(fields, files)
    headers = {'Content-Type': content_type}
    
    response = requests.post(url, data=body_str.encode('utf-8'), headers=headers)
    print(response.text)
    
# 要上传的文件
file = {
    'filename': 'example.txt',
    'data': open('path/to/example.txt', 'rb').read(),
    'mimetype': 'text/plain'
}

# 其他表单数据
fields = {
    'name': 'John',
    'email': 'john@example.com'
}

# 调用文件上传函数
upload_file('http://example.com/upload', fields, {'file': file})

在上述示例中,我们定义了一个upload_file()函数,接受三个参数:URL、其他表单数据和要上传的文件。然后我们先调用encode_multipart_formdata()函数将表单数据和文件编码为multipart/form-data格式,然后使用requests库发送POST请求,并将编码后的数据作为请求的body发送。

注意:在使用示例时,需要将url参数替换为实际的上传URL,path/to/example.txt替换为实际的文件路径。