Skip to main content
 首页 » 编程设计

python之上传二进制文件。编码问题

2024年11月01日10thcjp

我想使用 urllib2 将包含二进制数据的文件发送到服务器:

def encode_multipart_formdata(fields, files): 
    LIMIT = '----------lImIt_of_THE_fIle_eW_$' 
    CRLF = '\r\n' 
    L = [] 
    for (key, value) in fields: 
        L.append('--' + LIMIT) 
        L.append('Content-Disposition: form-data; name="%s"' % key) 
        L.append('') 
        L.append(str(value)) 
    for (key, filename, value) in files: 
        L.append('--' + LIMIT) 
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key,    str(filename))) 
        L.append('Content-Type: %s' % get_content_type(filename)) 
        L.append('') 
        L.append(value) 
    L.append('--' + LIMIT + '--') 
    L.append('') 
    body = CRLF.join(L) 
    content_type = 'multipart/form-data; boundary=%s' % LIMIT 
    return content_type, body 

使用:

    f = open(filePath, "rb") 
    content_type, body = encode_multipart_formdata([("param1",self.param1)], [("myfile", self.name, f.read())]) 
    request = urllib2.Request(url, body) 
    request.add_header('Content-type', content_type) 
    request.add_header('Content-length', str(len(body))) 
    response =  urllib2.urlopen(request) 

如果文件只包含 ascii 符号则一切正常。但是如果文件包含二进制数据,我在最后一串代码中有错误:

UnicodeDecodeError: 'ascii' codec can't decode byte 0x9a in position 271: ordinal not in range(128) 

如何对正文进行编码?服务器上的文件必须与客户端上的文件相同

请您参考如下方法:

错误表明您混合了 Unicode 数据和字节字符串。

您的文件数据仅包含字节字符串,这意味着您的其他 POST 值(字段 中的键和值)或文件名使用 unicode 值。首先将所有这些值编码为字节字符串。