# -*- coding:UTF-8 -*-
'''
Created on 2010-4-26
@author: shiyong
'''
import urllib
import sys
import urllib2
import mimetools, mimetypes
import os, stat
from IdongNet import IdongNet
from UserManager import UserManager
import cookielib
class Callable:
def __init__(self, anycallable):
self.__call__ = anycallable
# Controls how sequences are uncoded. If true, elements may be given multiple values by
# assigning a sequence.
doseq = 1
class MultipartPostHandler(urllib2.BaseHandler):
handler_order = urllib2.HTTPHandler.handler_order - 10 # needs to run first
def http_request(self, request):
data = request.get_data()
if data is not None and type(data) != str:
v_files = []
v_vars = []
try:
for(key, value) in data.items():
if type(value) == file:
v_files.append((key, value))
else:
v_vars.append((key, value))
except TypeError:
systype, value, traceback = sys.exc_info()
raise TypeError, "not a valid non-string sequence or mapping object", traceback
if len(v_files) == 0:
data = urllib.urlencode(v_vars, doseq)
else:
boundary, data = self.multipart_encode(v_vars, v_files)
contenttype = 'multipart/form-data; boundary=%s' % boundary
if(request.has_header('Content-Type')
and request.get_header('Content-Type').find('multipart/form-data') != 0):
print "Replacing %s with %s" % (request.get_header('content-type'), 'multipart/form-data')
request.add_unredirected_header('Content-Type', contenttype)
request.add_data(data)
return request
def multipart_encode(vars, files, boundary = None, buffer = None): #@NoSelf
if boundary is None:
boundary = mimetools.choose_boundary()
if buffer is None:
buffer = ''
for(key, value) in vars:
buffer += '--%s\r\n' % boundary
buffer += 'Content-Disposition: form-data; name="%s"' % key
buffer += '\r\n\r\n' + value + '\r\n'
for(key, fd) in files:
file_size = os.fstat(fd.fileno())[stat.ST_SIZE]
filename = os.path.basename(fd.name)
contenttype = mimetypes.guess_type(filename)[0] or 'application/octet-stream'
buffer += '--%s\r\n' % boundary
buffer += 'Content-Disposition: form-data; name="%s"; filename="%s"\r\n' % (key, filename)
buffer += 'Content-Type: %s\r\n' % contenttype
# buffer += 'Content-Length: %s\r\n' % file_size
fd.seek(0)
buffer += '\r\n' + fd.read() + '\r\n'
buffer += '--%s--\r\n\r\n' % boundary
return boundary, buffer
multipart_encode = Callable(multipart_encode)
https_request = http_request
class FileUploadMgr(object):
'''
管理系统文件上传
'''
def __init__(self):
'''
Constructor
'''
def upload_file(self,post_params):
'''
功能描述:上传文件
'''
cookies = cookielib.CookieJar()
opener = urllib2.build_opener(urllib2.HTTPCookieProcessor(cookies),MultipartPostHandler)
response = opener.open("http://us.i-dong.com/outer/server.action", post_params)
return response.read()
def upload_user_portrait(self,optType,width,height,portraitFile):
'''
功能描述:用户注册时或者更改个人信息的时候,上传自定义头像
参数说明:
optType string 标识图片作用参数 0:个人头像
width string 图片压缩宽带,如:'800'
height string 图片压缩高度,如:'600'
portraitFile File(Python的文件对象) 上传的文件,上传的文件类型为:jpeg、gif、bmp、png、pjpeg、x-png
返回值:xml文档字符串
'''
post_params = {}
post_params['userID'] = IdongNet.IdongID
post_params['version'] = IdongNet.version
post_params['webKey'] = IdongNet.webKey
post_params['optType'] = optType
post_params['width'] = width
post_params['height'] = height
post_params['portraitFile'] = portraitFile
post_params['key'] = 'uploadUserPortrait'
return self.upload_file(post_params)
if __name__ == '__main__':
print UserManager.login(1, '205599','123456')
fileuploadMgr = FileUploadMgr()
logofile = open('C:\\1.jpg','rb')
print fileuploadMgr.upload_user_portrait('0', '800' , '600', logofile)
Python HTTP文件上传
最新推荐文章于 2024-01-25 13:50:30 发布