# 简介
文章介绍的是使用tornado完成文件的上传功能
该项目的github地址: tornado_learning.git (opens new window)
# 栗子
设置文件上传的路径
代码: tornado_learning/settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
settings = {
"MEDIA_ROOT": os.path.join(BASE_DIR, "media"),
}
保存上传文件
获取前端传送过来的front_image
文件,然后再使用aiofiles
完成上传文件的二进制异步
写入。
代码: /apps/hello/uploadHandler.py
from tornado_learning.handler import BaseHandler
import os
import uuid
import aiofiles
class UploadHandler(BaseHandler):
async def post(self):
ret_data = {}
files_meta = self.request.files.get("front_image", None)
if not files_meta:
self.set_status(400)
ret_data["front_image"] = "请上传图片"
else:
for meta in files_meta:
filename = meta["filename"]
new_filename = "{uuid}_{filename}".format(uuid=uuid.uuid1(), filename=filename)
file_path = os.path.join(self.settings["MEDIA_ROOT"], new_filename)
async with aiofiles.open(file_path, "wb") as f:
await f.write(meta["body"])
ret_data['file_path'] = file_path
return self.finish(ret_data)