首页 > 技术文章 > tornado 后端通过http(第三方路径)传文件 eg:http://192.168.1.13//php/addmediadata.php (世邦音响)

meili970202 2019-11-20 10:33 原文

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())

##################上面的不能传文件名为汉字的文件#######################
#!/usr/bin/env python
# encoding: utf-8
import asyncio
import binascii
import six
import os
from io import BytesIO

from tornado.httpclient import AsyncHTTPClient, HTTPRequest


class HttpClient(object):
def __init__(self):
self.sess = AsyncHTTPClient()

async def get(self, url="", data=None):
params = "&".join("=".join(kv) for kv in data.items())
request = HTTPRequest(url=url + "?" + params, method="GET")
try:
resp = await self.sess.fetch(request)
content = resp.body.decode("utf-8")
return content
except Exception as e:
print("Error: %s" % e)

async def post(self, url=None, data=None, files=None):
if files is not None:
content_type, body = self.encode_multipart_formdata(data=data, files=files)
headers = {"Content-Type": content_type, 'content-length': str(len(body))}
else:
body = {} if data is None else "&".join("=".join([str(k), str(v)]) for k, v in data.items())
headers = {"Content-Type": "application/x-www-form-urlencoded"}
request = HTTPRequest(url=url, method="POST", headers=headers, body=body)
try:
resp = await self.sess.fetch(request)
content = resp.body.decode("utf-8")
return content
except Exception as e:
print("Error: %s" % e)
return

def choose_boundary(self):
"""
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_formdata(self, 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 = self.choose_boundary()
for key, value in data.items():
body.write(('--%s\r\n' % boundary).encode(encoding="utf-8"))
body.write(('Content-Disposition:form-data;name="%s"\r\n' % key).encode(encoding="utf-8"))
body.write('\r\n'.encode(encoding="utf-8"))
if isinstance(value, int):
value = str(value)
body.write(('%s\r\n' % value).encode(encoding="utf-8"))

for key, value in files.items():
body.write(('--%s\r\n' % boundary).encode(encoding="utf-8"))
body.write(('Content-Disposition:form-data;name="file";filename="%s"\r\n' % key).encode(encoding="utf-8"))
body.write('\r\n'.encode(encoding="utf-8"))
body.write(value)
body.write('\r\n'.encode(encoding="utf-8"))

body.write(('--%s--\r\n' % boundary).encode(encoding="utf-8"))
content_type = 'multipart/form-data;boundary=%s' % boundary
return content_type, body.getvalue()


zd_requests = HttpClient()


async def test_file_upload(file):
data = {"subpath": "", "unformat": "0"}
# files = {
# "菲儿 - 那片海.mp3": open("db.py", "rb").read()
# }
files = {
file.filename: file.body
}
request_url = "http://27.128.181.220:85/php/addmediadata.php"
resp = await zd_requests.post(url=request_url, data=data, files=files)
# print(str(resp.body.decode(encoding="utf-8")))


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

推荐阅读