手机主页网址大全,大型网站的优化方法,正规不收费的网站,做旅游网站怎样python版本是2.7#xff0c;使用urllib2将文件推送至微信#xff0c;在上传文件时#xff0c;碰到这样一个问题#xff1a;上传未经压缩的文本文件#xff0c;可以成功#xff1b;上传经过压缩的二进制文件#xff0c;则提示编码错误代码如下def upload_tmpfile_old(sel…python版本是2.7使用urllib2将文件推送至微信在上传文件时碰到这样一个问题上传未经压缩的文本文件可以成功上传经过压缩的二进制文件则提示编码错误代码如下def upload_tmpfile_old(self,filepath):try:#文件存在、文件可读、文件大小小于19Mif not (os.path.isfile(filepath) and os.access(filepath,os.R_OK)and os.path.getsize(filepath)19922944):return -1boundary ----------%s % hex(int(time.time() * 1000))data []data.append(--%s % boundary)fr open(filepath, rb)data.append(Content-Disposition: form-data; namemedia; filenamepickdump)data.append(Content-Type: application/octet-stream\r\n\r\n)data.append(fr.read())fr.close()data.append(--%s--\r\n % boundary)http_body \r\n.join(data)print http_bodysendurl https://qyapi.weixin.qq.com/cgi-bin/media/upload?access_token Token.gettoken() typefilereq urllib2.Request(sendurl, datahttp_body)req.add_header(Content-Type, multipart/form-data; boundary%s % boundary)req.add_header(Content-Length,len(http_body))print req.headersself.resp urllib2.urlopen(req, timeout5)print self.resp.__dict__print self.resp.read()except:logger.exception(上传文件出现异常)raiseif __name__ __main__:uploadfile wxRequest(WZ, , , file, 1000002)uploadfile.upload_tmpfile_old(/home/wz/12306.txt.zip)报错信息如下Traceback (most recent call last):File /home/wzk/wx2x/wxpush.py, line 264, in uploadfile.upload_tmpfile_old(/home/wzk/12306.txt.zip)File /home/wzk/wx2x/wxpush.py, line 227, in upload_tmpfile_oldself.resp urllib2.urlopen(req, timeout5)File /usr/lib64/python2.7/urllib2.py, line 154, in urlopenreturn opener.open(url, data, timeout)File /usr/lib64/python2.7/urllib2.py, line 431, in openresponse self._open(req, data)File /usr/lib64/python2.7/urllib2.py, line 449, in _open_open, req)File /usr/lib64/python2.7/urllib2.py, line 409, in _call_chainresult func(*args)File /usr/lib64/python2.7/urllib2.py, line 1242, in https_opencontextself._context)File /usr/lib64/python2.7/urllib2.py, line 1196, in do_openh.request(req.get_method(), req.get_selector(), req.data, headers)File /usr/lib64/python2.7/httplib.py, line 1057, in requestself._send_request(method, url, body, headers)File /usr/lib64/python2.7/httplib.py, line 1097, in _send_requestself.endheaders(body)File /usr/lib64/python2.7/httplib.py, line 1053, in endheadersself._send_output(message_body)File /usr/lib64/python2.7/httplib.py, line 895, in _send_outputmsg message_bodyUnicodeDecodeError: utf8 codec cant decode byte 0xb6 in position 149: invalid start byte以前用python3byte和str有明确的区分。这个功能由于版本问题只能用python2结果发现编码各种坑啊。压缩文件本来就是一个二进制文件不能被utf-8解码也是正常的不知道对于这个问题有没有方法解决PS 以前用requests的时候,是把文件读成bytes后直接拼回body里面的不知道这样做在python2中应该如何写