本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net
FastAPI 接受 POST 上传文件并保存本地,python
设置文件路径
读取成二进制数据,然后写入文件
import os
import uvicorn
from fastapi import FastAPI, File, UploadFile
app = FastAPI()
@app.post("/file/upload")
async def upload(file: UploadFile = File(...)):
fn = file.filename
save_path = f'./file/'
if not os.path.exists(save_path):
os.mkdir(save_path)
save_file = os.path.join(save_path, fn)
f = open(save_file, 'wb')
data = await file.read()
f.write(data)
f.close()
return {"msg": f'{fn}上传成功', 'length': len(data)}
if __name__ == '__main__':
uvicorn.run(app=app, host="0.0.0.0", debug=True)
标签:zhangphil,__,python,FastAPI,app,博客,file,path,save
From: https://www.cnblogs.com/zhuoss/p/16876833.html