Python 之 Sanic 实现上传文件功能

Python 框架 Sanic 实现文件上传功能

实现

判断允许上传的类型,同时利用 UUID 生成新的文件名存储到对应的文件夹中

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@app.route("/upload", methods=['POST'])
async def upload(request):
allow_type = ['.jpg', '.png', '.gif'] # 允许上传的类型
file = request.files.get('file')
type = os.path.splitext(file.name)

if type[1] not in allow_type:
return json({"code": -1, "msg": "只允许上传.jpg.png.gif类型文件"})

name = str(uuid4())+type[1]
path = "/user/data/web/upload" # 这里注意path是绝对路径

async with aiofiles.open(path+"/"+name, 'wb') as f:
await f.write(file.body)
f.close()
return json({"code": 0, "msg": "上传成功", "data": {
"name": name,
"url": "/upload/"+name
}})

上传

可以利用 Postman 上传测试,需要注意的是 header 头中的 Content-Type:multipart/form-data; 必须设置

访问

需要访问上传过后的文件,这就需要用到 Sanic 静态文件代理

1
2
path = "/user/data/web/upload" # 这里注意path是绝对路径
app.static("/upload", path)

最后访问路径为:

1
https://www.域名.com/upload/uuid.png