【问题标题】:validate file type and extention with fastapi UploadFile使用 fastapi UploadFile 验证文件类型和扩展名
【发布时间】:2021-09-15 11:35:25
【问题描述】:

我目前正在做一个小项目,其中涉及创建一个fastapi 服务器,允许用户上传一个jar 文件。

基本上我有这条路线:

@app.post("/upload")
async def upload(jar_file: UploadFile = File(...)):

我真的很想检查并验证该文件是否真的是jar 文件。

我可以自己实现它,但我很好奇fastapi 或任何其他包是否提供此功能。

【问题讨论】:

    标签: python rest fastapi


    【解决方案1】:

    您可以检查 MIME 类型 (https://fastapi.tiangolo.com/tutorial/request-files/#uploadfile)。

    @app.post("/upload")
    async def upload(jar_file: UploadFile = File(...)):
        if jar_file.content_type != "application/java-archive":
            raise HTTPException(400, detail="Invalid document type")
        return {"filename": "jar_file.filename"}
    

    【讨论】:

      猜你喜欢
      • 2011-04-07
      • 2014-08-15
      • 2016-02-15
      • 1970-01-01
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      • 2013-09-03
      • 1970-01-01
      相关资源
      最近更新 更多