2011-03-24 79 views
0

我想用下面的代碼上傳文件:當我執行的方法,它需要一個上傳文件內容需要很長的時間

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

你似乎沒有將你的請求正文發送到服務器,所以它可能被卡住,等待content-length字節到達,他們從來不會這樣做。

你肯定

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

不應該讀

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