如何使用unicode内容将文件上载到服务器?

2024-10-06 06:44:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我尝试使用以下代码将文件上载到服务器:

def build_request(self, theurl, fields, files, txheaders=None):
    content_type, body = self.encode_multipart_formdata(fields, files)
    if not txheaders: txheaders = {}
    txheaders['Content-type'] = content_type
    txheaders['Content-length'] = str(len(body))
    return urllib2.Request(theurl, body, txheaders)

def encode_multipart_formdata(self,fields, files, BOUNDARY = '-----'+mimetools.choose_boundary()+'-----'):
    ''' from www.voidspace.org.uk/atlantibots/pythonutils.html '''
    CRLF = '\r\n'
    L = []
    if isinstance(fields, dict):
        fields = fields.items()
    for (key, value) in fields:
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"' % key)
        L.append('')
        L.append(value)
    for (key, filename, value) in files:
        filetype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
        L.append('--' + BOUNDARY)
        L.append('Content-Disposition: form-data; name="%s"; filename="%s"' % (key, filename))
        L.append('Content-Type: %s' % filetype)
        L.append('')
        L.append(value)
    L.append('--' + BOUNDARY + '--')
    L.append('')
    body = CRLF.join(L)
    content_type = 'multipart/form-data; boundary=%s' % BOUNDARY
    return content_type, body

mp3 = ('file', file, open(file,'rb').read())
url = self.build_request(upload_url, {}, (mp3,))
res = urllib2.urlopen(url)

我上传mp3文件(0001.mp3),得到以下错误-

(type 'exceptions.UnicodeDecodeError', UnicodeDecodeError('ascii', '-------192.1xx.xx.xx.501.5413.1420317280.341.1-----\r\nContent-Disposition: form-data; name="file"; filename="/Users/Me/Music/0001.mp3"\r\nContent-Type: audio/mpeg\r\n\r\nID3\x04\x00\x00\x00\x00\x00#TSSE\x00\x00\x00\x0f\x00\x00\x03Lavf55.33.100\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xfb\x94\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00Info\x00\x00\x00\x07\x00\x00#\xf9\x005\xf7\x00\x00\x02\x05\x08\n\r\x10\x12\x14\x17\x19\x1c\x1f!$\'(+.0368;=@BEHJMOQTWY\_acfhknpsvxz}\x80\x82\x85\x88\x89\x8c\x8f\x91\x94\x97\x99\x9c\x9e\xa1\xa3\xa6\xa9\xab\xae\xb1......UUUUU', 45, 46, 'ordinal not in range(128)'), )

怎么了?在

升级版。完整的回溯如下:

^{pr2}$

Tags: keyselffieldsvaluetypebodyfilescontent
1条回答
网友
1楼 · 发布于 2024-10-06 06:44:49

异常回溯显示Python试图解码您的请求体;因为它是二进制数据,Python用于隐式解码(ASCII)的默认编码在这里失败。在

Python试图解码您的请求体,因为要发送到服务器的第一部分HTTP头(包括带有方法、路径和HTTP版本的初始请求行)已经是一个unicode对象。如果URL的头文件中至少有一个是unicode对象,而其余部分可以被解码为ASCII,则会发生这种情况。在

确保您的头和URL编码为字节。如果不是ASCII,则需要显式地对它们进行编码;报头通常使用Latin1或不透明字节(http1.0提供了一个从未使用过的mime兼容编码选项),URL必须是ASCII,其中任何路径元素或查询参数都编码为UTF-8,然后再进行URL编码(示例代码请参见how to deal with ® in url for urllib2.urlopen?)。在

不要假设这是一个额外的URL,因为这是一个额外的URL:

url = self.build_request(upload_url.encode('ascii'), {}, (mp3,))

相关问题 更多 >