Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/363.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何使用unicode内容将文件上载到服务器?_Python_Python 2.7_File Upload_Unicode_Urllib2 - Fatal编程技术网

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

Python 如何使用unicode内容将文件上载到服务器?,python,python-2.7,file-upload,unicode,urllib2,Python,Python 2.7,File Upload,Unicode,Urllib2,我尝试使用以下代码将文件上载到服务器: 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

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

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)时出现以下错误-

(输入'exceptions.UnicodeDecodeError',UnicodeDecodeError('ascii'), '----192.1xx.xx.xx.501.5413.1420317280.341.1-----\r\n内容配置:表单数据;name=“文件”; filename=“/Users/Me/Music/0001.mp3”\r\n内容类型: \r\n\\r\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\x00\x00\x00\x00\x00\x00\x00Info\x00\x00\x00\x07\x00\x00\x00\x09\x005\xf7\x00\x00\x00\x02\x05\x08\n\r\x10\x12\x14\x17\x19\x1c\x1f!$\'(++.0368;=@BEHJMOQTWY\\uACFHKNPSVxZ}\x80\x82\x85\x88\x89\x8c\x8f\x91\x94\x97\x99\x9c\x9e\xa1\xa3\xa6\xa9\xab\xae\xb1……uuuuuuuuu', 45,46,'序号不在范围内(128)',)

怎么了

Upd。完整回溯如下:

Traceback (most recent call last):
  File "test.py", line 258, in <module>
    upload()
  File "test.py", line 242, in upload
    success = uploadFile(file)
  File "test.py", line 179, in uploadFile
    res = urllib2.urlopen(url)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 127, in urlopen
    return _opener.open(url, data, timeout)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 404, in open
    response = self._open(req, data)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 422, in _open
    '_open', req)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 382, in _call_chain
    result = func(*args)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1214, in http_open
    return self.do_open(httplib.HTTPConnection, req)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 1181, in do_open
    h.request(req.get_method(), req.get_selector(), req.data, headers)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 973, in request
    self._send_request(method, url, body, headers)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 1007, in _send_request
    self.endheaders(body)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 969, in endheaders
    self._send_output(message_body)
  File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py", line 827, in _send_output
    msg += message_body
UnicodeDecodeError: 'ascii' codec can't decode byte 0xff in position 220: ordinal not in range(128)
回溯(最近一次呼叫最后一次):
文件“test.py”,第258行,在
上传()
上传文件“test.py”,第242行
成功=上载文件(文件)
上传文件中第179行的文件“test.py”
res=urlib2.urlopen(url)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py”,urlopen中的第127行
return\u opener.open(url、数据、超时)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py”,第404行,打开
响应=自身打开(请求,数据)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py”,第422行,打开
"开放",
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py”,第382行,在调用链中
结果=func(*args)
http_open中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py”,第1214行
返回self.do_open(httplib.HTTPConnection,req)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py”,do_open中的第1181行
h、 请求(请求获取方法(),请求获取选择器(),请求数据,标题)
请求中的文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py”,第973行
self.\u发送请求(方法、url、正文、标题)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py”,第1007行,在发送请求中
self.endheaders(主体)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py”,第969行,在endheaders中
自发送输出(消息体)
文件“/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/httplib.py”,第827行,在“发送”输出中
msg+=消息体
UnicodeDecodeError:“ascii”编解码器无法解码位置220处的字节0xff:序号不在范围内(128)

异常回溯显示Python试图解码您的请求正文;由于它是二进制数据,Python用于隐式解码(ASCII)的默认编码在此失败

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

确保您的标题和URL编码为字节。如果它们不是ASCII码,则需要对它们进行显式编码;标题通常使用拉丁1或不透明字节(HTTP 1.0提供了一个mime兼容的编码选项,从来没有人使用过),URL必须是ASCII,带有任何路径元素或查询参数,编码为UTF-8,然后进行URL编码(参见示例代码)

因为您没有传入额外的头,所以我假设您的URL是
unicode
对象:

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

错误的完整回溯是什么?@MartijnPieters,我已经用回溯更新了问题。你有一个unicode头。你要发送什么标题?这可能包括URL。@MartijnPieters,我不会手动向标题添加任何内容,也就是说,标题是根据上面的代码生成的。@MartijnPieters,你是对的-问题是使用了Unicode URL,请将其作为答案发布,因此我将删除我的标题并接受你的。