首页 > 编程语言 >simpread-(127 条消息) FastAPI 接受 POST 上传文件并保存本地,python_zhangphil 的博客 - CSDN 博客

simpread-(127 条消息) FastAPI 接受 POST 上传文件并保存本地,python_zhangphil 的博客 - CSDN 博客

时间:2022-11-10 14:13:54浏览次数:70  
标签:zhangphil __ python FastAPI app 博客 file path save

本文由 简悦 SimpRead 转码, 原文地址 blog.csdn.net

FastAPI 接受 POST 上传文件并保存本地,python

设置文件路径

image-20221108190155252

读取成二进制数据,然后写入文件

image-20221108190230403

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

相关文章