2012-07-18 66 views
3

我有一個服務器,我正在嘗試建立一個發送請求以獲取數據。我認爲實現這一目標的一種方法是在頭中添加參數併發出請求。但是我收到了很少的錯誤,我不能很好地理解這些錯誤。Python:發送圖像文件的請求

HTML表單

<html> 
<head> 
<meta http-equiv="content-type" content="text/html; charset=ISO-8859-1"> 
    </head> 
    <body> 
    <form method="POST" action="http://some.server.com:61235/imgdigest" enctype="multipart/form-data"> 
     quality:<input type="text" name="quality" value="2"><br> 
     category:<input type="text" name="category" value="1"><br> 
     debug:<input type="text" name="debug" value="1"><br> 
     image:<input type="file" name="image"><br> 
     <input type="submit" value="Submit"> 
    </form> 
    </body> 
</html> 

Python代碼:我已編輯基於答案

import urllib, urllib2 
import base64 

if __name__ == '__main__': 
    page = 'http://some.site.com:61235/' 
    with open("~/image.jpg", "rb") as image_file: 
     encoded_image = base64.b64encode(image_file.read()) 
    raw_params = {'quality':'2','category':'1','debug':'0', 'image': encoded_image} 
    params = urllib.urlencode(raw_params) 
    request = urllib2.Request(page, params) 
    request.add_header("Content-type", "application/x-www-form-urlencoded; charset=UTF-8") 
    page = urllib2.urlopen(request) 
    info = page.info() 

錯誤的問題:

page = urllib2.urlopen(request) 
    File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 126, in urlopen 
    return _opener.open(url, data, timeout) 
    File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 406, in open 
    response = meth(req, response) 
    File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 519, in http_response 
    'http', request, response, code, msg, hdrs) 
    File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 444, in error 
    return self._call_chain(*args) 
    File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 378, in _call_chain 
    result = func(*args) 
    File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/urllib2.py", line 527, in http_error_default 
    raise HTTPError(req.get_full_url(), code, msg, hdrs, fp) 
urllib2.HTTPError: HTTP Error 404: Not Found 
+0

那麼使用encoded_image而不是「~/image.jpg」,一方面,圖像需要有一個圖像,而不是一個字符串。我會建議嘗試請求,而不是使用urllib,urllib2。 http://docs.python-requests.org/en/latest/index.html – sberry 2012-07-18 22:27:44

回答

4

添加這個頭:

request.add_header("Content-type", "application/x-www-form-urlencoded; charset=UTF-8") 

此外,您發送的圖像參數是一個字符串,而不是圖像文件的內容。你需要B64編碼它

import base64 

with open("image.jpg", "rb") as image_file: 
    encoded_image = base64.b64encode(image_file.read()) 

然後在raw_params

+0

所以我應該在request = urllib2.Request(page,params)之後將它添加到頭部? – 2012-07-19 21:53:01

+0

我做了更改,但仍然收到相同的錯誤。 – 2012-07-19 23:21:37

+1

確保您在Python代碼中使用的網址與html表單中的操作屬性完全相同。看起來你正在Python中添加'.html'。 – 2012-07-20 15:08:52