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

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




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

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

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

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
FastAPI中,你可以使用`request`对象的`files`属性来获取通过POST请求提交的文件数据。然后,你可以使用Python的MySQL连接库(如`mysql-connector-python`)将图片保存到MySQL数据库中。以下是一个示例代码: ```python from fastapi import FastAPI, UploadFile import mysql.connector app = FastAPI() def save_image_to_mysql(image_data): conn = mysql.connector.connect( host='localhost', user='your_username', password='your_password', database='your_database' ) cursor = conn.cursor() # 将图片数据插入到数据库中 insert_query = "INSERT INTO images (image_blob) VALUES (%s)" cursor.execute(insert_query, (image_data,)) # 提交更改并关闭连接 conn.commit() cursor.close() conn.close() @app.post("/upload_image") async def upload_image(image: UploadFile): # 读取图片数据 image_data = image.file.read() # 保存图片到MySQL数据库 save_image_to_mysql(image_data) return {"message": "Image uploaded successfully"} ``` 在上面的代码中,你需要替换以下部分: - `your_username`:你的MySQL用户名 - `your_password`:你的MySQL密码 - `your_database`:你要连接的MySQL数据库名称 - `images`:你的表名,需要在数据库中创建一个包含 `image_blob` 列的表 在这个示例中,我们定义了一个路由 `/upload_image` 来处理POST请求。通过`UploadFile`参数,我们可以获取到上传的图片数据。然后,我们调用`save_image_to_mysql`函数将图片数据保存到MySQL数据库中。 请确保已经正确安装了 `fastapi` 和 `mysql-connector-python` 库,可以使用 `pip install fastapi mysql-connector-python` 进行安装。另外,还需要安装一个ASGI服务器(如`uvicorn`)来运行FastAPI应用。 这样,通过POST请求上传的图片将被保存到后端MySQL数据库中。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坦笑&&life

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值