You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用fetch提交GQLGen文件上传时,如何确保File被正确读取?

问题根源

你遇到的问题核心有两点:

  1. File对象无法被JSON序列化:JSON.stringify处理File对象时会直接转为空对象{},这就是variables里file值为空的原因。
  2. GraphQL文件上传不支持application/json请求头:标准GraphQL文件上传要求用multipart/form-data格式发送请求,而非JSON格式。
解决方案

修改前端代码,改用FormData构造符合GraphQL multipart规范的请求:

HTML (Svelte) 保持不变

<form on:submit|preventDefault={submit}>
    <input type="file" id="myFile" name="filename">
    <input type="submit">
</form>

修改后的TS代码

function submit() {
    const fileInput = document.getElementById('myFile') as HTMLInputElement;
    const file = fileInput.files?.[0];
    if (!file) return;

    const formData = new FormData();
    // 构造GraphQL查询内容
    const query = `mutation($file: Upload!) {
        imageUpload(file: $file) {
            serverResponseMessage
        }
    }`;
    // 传入query和占位的variables(文件位置用null)
    formData.append('operations', JSON.stringify({
        query,
        variables: { file: null }
    }));
    // 定义文件与variables字段的映射关系
    formData.append('map', JSON.stringify({
        '0': ['variables.file']
    }));
    // 添加文件,key需和map中的索引对应
    formData.append('0', file);

    fetch('http://localhost:8080/query', {
        method: 'POST',
        body: formData // 浏览器会自动设置正确的Content-Type
    })
    .then(res => res.json())
    .then(data => console.log(data))
    .catch(err => console.error(err));
};
关键说明
  • operations字段:包含GraphQL的query和占位的variables,文件位置用null占位
  • map字段:告诉服务器上传的文件对应variables里的哪个字段,示例中'0': ['variables.file']表示key为0的文件对应variables.file
  • 无需手动设置Content-Type:浏览器会自动为FormData添加带boundary分隔符的multipart/form-data头,避免手动设置导致的格式错误

调整后服务器就能正确识别Upload类型参数,不会再返回map[string]interface {} is not an Upload错误。

内容的提问来源于stack exchange,提问作者user2781522

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 00:30:57