首页 > Web开发 > 详细

tornado 后端通过http(第三方路径)传文件

时间:2019-11-20 12:58:47      阅读:166      评论:0      收藏:0      [点我收藏+]
import asyncio
import binascii
import six
import os
from io import BytesIO
from tornado.httpclient import AsyncHTTPClient, HTTPRequest


def choose_boundary():
"""
Our embarrassingly-simple replacement for mimetools.choose_boundary.
"""
boundary = binascii.hexlify(os.urandom(16))
if six.PY3:
boundary = boundary.decode(‘ascii‘)
return boundary


def encode_multipart_formdata3(data=None, files=None):
"""
fields is a sequence of (name, value) elements for regular form fields.
files is a sequence of (name, filename, value) elements for data to be
uploaded as files.
Return (content_type, body) ready for httplib.HTTP instance
"""
body = BytesIO()
boundary = choose_boundary()
for key, value in data.items():
body.write(six.b(‘--%s\r\n‘ % boundary))
body.write(six.b(‘Content-Disposition:form-data;name="%s"\r\n‘ % str(key)))
body.write(six.b(‘\r\n‘))
body.write(six.b(‘%s\r\n‘ % value))

for key, value in files.items():
body.write(six.b(‘--%s\r\n‘ % boundary))
body.write(six.b(‘Content-Disposition:form-data;name="file";filename="%s"\r\n‘ % key))
body.write(six.b(‘\r\n‘))
body.write(value)
body.write(six.b(‘\r\n‘))

body.write(six.b(‘--%s--\r\n‘ % boundary))
content_type = ‘multipart/form-data;boundary=%s‘ % boundary
return content_type, body.getvalue()


async def file_uploading(): #使用前段传来的文件是,在这里填一个file
print(1111111111111)
data = {"subpath": "", "unformat": "0"}
files = {
"1.mp3": open("1.mp3", "rb").read() #这个是本地文件
}
# files = {
# file.filename: file.body # 这个是前段传来的文件
# }
content_type, body = encode_multipart_formdata3(data=data, files=files)
client = AsyncHTTPClient()
request_url = "http://27.128.181.220:85/php/addmediadata.php"
request = HTTPRequest(
url=request_url,
method="POST",
headers={"Content-Type": content_type, ‘content-length‘: str(len(body))},
body=body
)
resp = await client.fetch(request)
print(str(resp.body.decode(encoding="utf-8")))
return str(resp.body.decode(encoding="utf-8"))


if __name__ == "__main__":
loop = asyncio.get_event_loop()
loop.run_until_complete(file_uploading())

tornado 后端通过http(第三方路径)传文件

原文:https://www.cnblogs.com/meili970202/p/11896046.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!