首页
/ Strawberry GraphQL 文件上传功能配置指南

Strawberry GraphQL 文件上传功能配置指南

2025-06-14 13:32:25作者:邬祺芯Juliet

在最新版本的 Strawberry GraphQL 框架中,文件上传功能默认被禁用。本文详细介绍了如何正确配置 FastAPI 集成环境下的多文件上传功能。

问题背景

开发者在使用 Strawberry GraphQL 时,按照官方文档示例实现多文件上传接口时,可能会遇到"Unsupported content type"错误。这是由于框架从 0.243.0 版本开始,出于安全考虑默认禁用了 multipart 上传功能。

解决方案

对于 FastAPI 集成环境,需要在创建 GraphQLRouter 时显式启用 multipart 上传功能:

from fastapi import FastAPI
from strawberry.fastapi import GraphQLRouter

app = FastAPI()

# 关键配置:添加 multipart_uploads_enabled=True 参数
graphql_app = GraphQLRouter(schema, multipart_uploads_enabled=True)
app.include_router(graphql_app, prefix="/graphql")

实现细节

  1. Schema 定义:在 GraphQL schema 中,使用 Upload 类型来声明文件上传字段:
@strawberry.mutation
def read_files(files: List[Upload]) -> List[str]:
    contents = []
    for file in files:
        content = file.read().decode("utf-8")
        contents.append(content)
    return contents
  1. 请求格式:客户端需要使用 multipart/form-data 格式发送请求,包含三个主要部分:

    • operations:包含 GraphQL 查询和变量
    • map:文件与变量的映射关系
    • 实际文件内容
  2. curl 示例

curl --location 'localhost:7675/graphql' \
--form 'operations="{ \"query\": \"mutation(\$files: [Upload\!]\!) { readFiles(files: \$files) }\", \"variables\": { \"files\": [null, null] } }"' \
--form 'map="{\"file1\": [\"variables.files.0\"], \"file2\": [\"variables.files.1\"]}"' \
--form 'file1=@"/path/to/file1.csv"' \
--form 'file2=@"/path/to/file2.csv"'

最佳实践

  1. 生产环境中建议对上传文件大小进行限制
  2. 考虑添加文件类型验证逻辑
  3. 对于大文件,建议实现流式处理而非一次性读取
  4. 注意文件描述符的及时关闭

版本兼容性

此配置方式适用于 Strawberry GraphQL 0.243.0 及以上版本。对于更早版本,multipart 上传功能默认是启用的,无需额外配置。

通过以上配置,开发者可以顺利实现基于 Strawberry GraphQL 的文件上传功能,同时保持框架的安全性和灵活性。

登录后查看全文
热门项目推荐
相关项目推荐