当前位置: 移动技术网 > IT编程>脚本编程>Python > python 使用poster模块进行http方式的文件传输到服务器的方法

python 使用poster模块进行http方式的文件传输到服务器的方法

2019年03月21日  | 移动技术网IT编程  | 我要评论

时代影视杂志社,必利劲,奶油森林

这几天帮内部人员做一个文件传输的小工具,要用http的方式,在用django搭建了个小框架之后,如何进行传输,特别是大文件的传输,成为主要问题。经过查资料,最后选择了通过poster这个模块来进行文件的传输,方式如下:

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方式的文件传输到服务器的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持移动技术网。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网