我想使用Python 2.7,不带任何不在标准库中的模块,将文件上传到网络服务器(它将接受此类请求)。
我知道这可以通过将数据作为多部分表单数据的一部分上传来完成,但是我想知道是否可以使用 Content-Type: application/pdf
来 POST
> (例如)和 Content-Length
设置为文件的长度,并且将帖子的内容设置为(在本例中为 PDF)文件的内容。
如果是这样,最简单的方法是什么?
最佳答案
如果服务器接受直接有效负载发布(而不是文件作为 multipart/form-data
POST 请求的一部分),您只需设置 Request()
data 参数为文件数据:
import urllib2
with open(filename, 'rb') as uploadfile:
request = urllib2.Request(url, data=uploadfile.read(),
{'Content-Type': 'application/pdf'})
response = urllib2.urlopen(request)
urllib2.Request
对象对 data
的内容不做任何假设,除了 Content-Type
header 将设置为application/x-www-form-urlencoded
如果设置了 data
,除非您提供自己的数据。
执行此操作时,将为您设置 Content-Length
header 。
关于python - 在 Python 中上传文件内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31861013/