使用Python上传图像文件

2 投票
2 回答
3291 浏览
提问于 2025-04-16 02:52

有没有办法用Python上传一个图片文件呢?我可以通过下面的代码在一个简单的HTML页面上上传文件。但我想知道能不能通过Python程序来实现这个功能。可以用urllib2模块来做到吗?有没有什么例子可以参考一下?

请帮帮我。谢谢。

<form action="http://somesite.com/handler.php" method="post" enctype="multipart/form-data">

<table>

        <tr><td>File:</td><td><input type="file" name="file" /></td></tr>

        <tr><td><input type="submit" value="Upload" /></td></tr>

</table>

</form>

2 个回答

6

你可以使用pycurl这个包来实现这个功能。

from StringIO import StringIO
from pycurl import *
c = Curl()
d = StringIO()
h = StringIO()
c.setopt(URL, "http://somesite.com/handler.php")
c.setopt(POST, 1)
c.setopt(HTTPPOST, [('file', (FORM_FILE, '/path/to/file')), ('submit', 'Upload')])
c.setopt(WRITEFUNCTION, d.write)
c.setopt(HEADERFUNCTION, h.write)
c.perform()
c.close()

撰写回答