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)