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())
原文:https://www.cnblogs.com/meili970202/p/11896046.html