使用FastAPI上载文件 [英] Upload file using fastapi

查看:0
本文介绍了使用FastAPI上载文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Fastapi根据官方文档上传文件,就像:

@app.post("/create_file/")
async def create_file(file: UploadFile=File(...)):
      file2store = await file.read()
      # some code to store the BytesIO(file2store) to the other database

当我使用python请求发送请求时,lib:

f = open(".../file.txt", 'rb')
files = {"file": (f.name, f, "multipart/form-data")}
requests.post(url="SERVER_URL/create_file", files=files)

文件2存储始终为空。有时(很少见),它可以获得文件字节,但几乎所有的时间都是空的,所以我不能恢复另一个数据库上的文件。 我也尝试了‘bytes’而不是‘UploadFile’,我得到了同样的结果。 是我的代码中有什么地方错了,还是我用FastAPI上传文件的方式错了?我在谷歌上搜索了很长时间才找到一些答案,但失败了。所以我在这里提出这个问题,希望知道答案的人能帮我解决问题。谢谢

推荐答案

@app.post("/create_file/")
async def image(image: UploadFile = File(...)):
    print(image.file)
    # print('../'+os.path.isdir(os.getcwd()+"images"),"*************")
    try:
        os.mkdir("images")
        print(os.getcwd())
    except Exception as e:
        print(e) 
    file_name = os.getcwd()+"/images/"+image.filename.replace(" ", "-")
    with open(file_name,'wb+') as f:
        f.write(image.file.read())
        f.close()
   file = jsonable_encoder({"imagePath":file_name})
   new_image = await add_image(file)
   return {"filename": new_image}

这篇关于使用FastAPI上载文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆