如何在python中使用poster模块将文件以http方式传输到服务器

如何在python中使用poster模块将文件以http方式传输到服务器?针对这个问题,这篇文章详细介绍了相对应的分析和解答,希望可以帮助更多想解决这个问题的小伙伴找到更简单易行的方法。

方式如下:

from poster.encode import multipart_encode
from poster.streaminghttp import register_openers
import urllib2
def upload_file(url,upload_file_path,filename):
 register_openers()
 datagen, headers = multipart_encode({"file": open(upload_file_path, "rb"),"type":"uploadFile","filename":filename})
 request = urllib2.Request(url, datagen, headers)
 return urllib2.urlopen(request).read()

poster的用法可以参考官方文件:点击打开链接

其中,url为服务器的接收url,upload_file_path 为文件的绝对路径,filename是文件名称,当然这里我只是贴了上传文件的代码,认证方式可以根据自己的需要进行补充。这个代码放在客户端上,当接收到服务端要上传的文件时,将文件上传给服务端。

服务端在接收到这个文件流时,文件数据会保存在request的FILE信息中,可以通过这样的方式进行接收:

with open(full_path,'wb+') as f:
 for chunk in request.FILES.get('file').chunks():
 f.write(chunk)

full_path为保存的路径。

关于如何在python中使用poster模块将文件以http方式传输到服务器问题的解答就分享到这里了,希望以上内容可以对大家有一定的帮助,如果你还有很多疑惑没有解开,可以关注行业资讯频道了解更多相关知识。