在python中上传文件内容需要很长时间

时间:2011-03-24 10:56:44

标签: python upload multipart httplib

我正在尝试使用以下代码上传文件:

url = "/folder/sub/interface?"
connection = httplib.HTTPConnection('www.mydomain.com')

def sendUpload(self):
    fields = []
    file1 = ['file1', '/home/me/Desktop/sometextfile.txt']
    f = open(file1[1], 'r')
    file1.append(f.read())
    files = [file1]
    content_type, body = self.encode_multipart_formdata(fields, files)

    myheaders['content-type'] = content_type
    myheaders['content-length'] = str(len(body))

    upload_data = urllib.urlencode({'command':'upload'})
    self.connection.request("POST", self.url + upload_data, {}, myheaders)
    response = self.connection.getresponse()
    if response.status == 200:
        data = response.read()
        self.connection.close()
        print data

encode_multipart_formdata()来自http://code.activestate.com/recipes/146306/

当我执行该方法时,需要很长时间才能完成。事实上,我认为它不会结束..在网络监视器上,我看到数据被传输,但方法并没有结束......

为什么?我应该在某处设置超时吗?

1 个答案:

答案 0 :(得分:1)

您似乎没有将请求的主体发送到服务器,因此它可能会等待content-length个字节到达,这是他们从未做过的。

你确定吗

self.connection.request("POST", self.url + upload_data, {}, myheaders)

不应该阅读

self.connection.request("POST", self.url + upload_data, body, myheaders)