以下是单个文件的,不确定你的文件夹是什么意思,可以压缩下再上传(方法一样,调用zip命令)
我的实现方法:调用终端的curl,以下为代码平片段,实现的功能是上传log文件到服务器,供参考:
def post_log(self, post_url, del_source_file=True):'''
post log to log server
'''
if self.log_path:
command = "curl -s -F log=@{0} {1}".format(self.log_path, post_url)
return_str = os.popen(command).read()
logging.debug(return_str)
# print return_str
if return_str == "success":
if del_source_file:
del_command = "sudo rm {0}".format(self.log_path)
os.system(del_command)
return True
else:
return False
return False
首先,标准HTTP协议对上传文件等表单的定义在这里:wwwietforg/rfc/rfc1867txt 大概数据包格式如下:单文件:
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-dataname="field1"
Joe Blow
--AaB03x
content-disposition: form-dataname="pics"filename="file1.txt"
Content-Type: text/plain
... contents of file1.txt ...
--AaB03x--
多文件:
Content-type: multipart/form-data, boundary=AaB03x
--AaB03x
content-disposition: form-dataname="field1"
Joe Blow
--AaB03x
content-disposition: form-dataname="pics"
Content-type: multipart/mixed, boundary=BbC04y
--BbC04y
Content-disposition: attachmentfilename="file1.txt"
其次,python上传文件的几种方法:
1 自己封装HTTP的POST数据包:http//stackoverflowcom/questions/680305/using-multipartposthandler-to-post-form-data-with-python
import httplibimport mimetypesdef post_multipart(host, selector, fields, files): content_type, body = encode_multipart_formdata(fields, files) h = httplib.HTTP(host) h.putrequest('POST', selector) h.putheader('content-type', content_type) h.putheader('content-length', str(len(body))) h.endheaders() h.send(body) errcode, errmsg, headers = h.getreply() return h.file.read() 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-dataname="%s"' % key) L.append('') L.append(value) for (key, filename, value) in files: