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

React+Inertia.js中useForm无法设置File字段问题求助

问题解决:Inertia.js + React 中文件无法通过useForm设置的问题

核心问题

你遇到的问题根源在于给file类型的input绑定了value={data.file},以及一处代码笔误:

  1. File类型的input是特殊受控组件,不能直接将File对象赋值给value属性——这会导致React无法正确跟踪文件选中状态,进而让useForm的setData无法更新file字段。
  2. 代码中setFile(null)是未定义的函数,属于笔误。

修复步骤

1. 移除input的value绑定

修改文件输入框代码,删掉value={data.file}:

<input type="file"
       id="document_pdf"
       name="file"
       accept=".pdf,application/pdf"
       className="mt-1 block w-full"
       onChange={handleFileChange}
/>

2. 修正笔误

把handleFileChange里的setFile(null)改成setData('file', null):

const handleFileChange = (e) => {
    const file = e.target.files[0];
    console.log(file);
    if (file && file.type === 'application/pdf') {
        setData('file', file);
        setData('filename', file.name);
        console.log("File attached");
    } else {
        // 修正此处笔误
        setData('file', null);
        setData('filename', '');
        console.log("No file attached");
    }
};

3. 提交表单(无需手动创建FormData)

Inertia的useForm会自动识别File对象,提交时自动转为multipart/form-data请求,直接调用post方法即可:

const handleSubmit = () => {
    post('/your-submit-url');
};

验证

修改完成后,点击调试按钮查看data.file,应该能正常显示选中的File对象,提交表单时后端也能接收到文件。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.17 07:53:11