ReactJS+Django+GraphQL文件上传异常:文件参数为空对象
React GraphQL 文件上传为空对象的解决方案
我在React前端上传文件,通过GraphQL发送到Django后端时,GraphQL请求里的file参数是空对象,Django用graphene-file-upload接收的也是空字典。
问题相关代码
前端React代码
function Integrations() { const [importTranscations] = useMutation(IMPORT_TRANSACTIONS); function onChange({ target: { validity, files: [file], }, }) { if (validity.valid) { importTranscations({ variables: { file } }); } } return ( <div style={{ padding: "20px", }} > <input type="file" required onChange={onChange} /> </div> ); } export default Integrations;
Django后端URL配置
from django.urls import path from django.contrib import admin from django.views.decorators.csrf import csrf_exempt from graphene_file_upload.django import FileUploadGraphQLView urlpatterns = [ path("admin/", admin.site.urls), path("graphql/", csrf_exempt(FileUploadGraphQLView.as_view())), ]
Django后端Mutation代码
import graphene from graphene_file_upload.scalars import Upload class ImportTransactionsMutation(graphene.Mutation): class Arguments: file = Upload(required=True) task_id = graphene.String() def mutate(self, info, file): print("@@ DEBUGGING @@ -> file", file) task_id = "sample" return ImportTransactionsMutation(task_id=task_id)
控制台输出
@@ DEBUGGING @@ -> file {}
问题原因及解决方法
问题核心是GraphQL默认的JSON请求格式无法正确传递File对象,必须使用multipart/form-data格式发送请求,需要从前端配置入手调整:
配置Apollo Client支持文件上传
替换默认的createHttpLink为apollo-upload-client提供的createUploadLink,确保Client能自动处理文件上传的请求格式:import { ApolloClient, InMemoryCache } from '@apollo/client'; import { createUploadLink } from 'apollo-upload-client'; const client = new ApolloClient({ link: createUploadLink({ uri: '/graphql', // 你的GraphQL端点地址 }), cache: new InMemoryCache(), });确认Mutation定义类型
保证前端Mutation中file参数的类型为Upload:import { gql } from '@apollo/client'; const IMPORT_TRANSACTIONS = gql` mutation ImportTransactions($file: Upload!) { importTransactions(file: $file) { taskId } } `;后端无需额外调整
你已经使用了FileUploadGraphQLView,这部分配置是正确的。前端调整后,后端就能接收到完整的文件对象(实际是Django的InMemoryUploadedFile或TemporaryUploadedFile实例),控制台打印的file将不再是空字典。
内容的提问来源于stack exchange,提问作者Sreekar Mouli
相关产品推荐
相关产品推荐

