React中FormData上传文件时file字段为空对象的问题排查
React文件上传FormData中file字段为空对象问题排查
问题场景
React项目中通过FormData上传文件时,提交后file字段变为空对象{},引发后端报错。相关代码及提交模型数据如下:
原代码
for (let i = 0; i < selectedFiles.length; i++) { const rand = uuidv4() const form = new FormData(); form.append('TicketId', inFuncResult); form.append('Title', title); form.append('Description', body); form.append('LatinCode', 'ldj3556'); form.append('file', JSON.stringify(selectedFiles[i])); // form.append("file", new Blob([selectedFiles[i]], {type: 'application/octet-stream'})); form.append('fileType', 'Warranty'); form.append('Id', rand); const myForm = JSON.stringify(Object.fromEntries(form)); await TicketFileAPI.post( "/TicketFile", form, ); }
提交后模型数据
{"TicketId":"2ca3c87d-65d4-ed11-afe9-e4fd45c4a1fc","Title":"wqe","Description":"sadasd","LatinCode":"ldj3556","file":{},"fileType":"Warranty","Id":"13602769-5dab-4033-81a2-cc7b20f13459"}
问题原因
- 错误序列化File对象:用
JSON.stringify(selectedFiles[i])处理File对象时,由于File的核心属性不可枚举,序列化后只能得到空对象{},导致后端无法获取文件内容。 - 多余的Blob包装:注释里尝试用
new Blob([selectedFiles[i]])包装File对象完全没必要,File本身就是Blob的子类,直接传入FormData即可。
修正后的代码
for (let i = 0; i < selectedFiles.length; i++) { const rand = uuidv4() const form = new FormData(); form.append('TicketId', inFuncResult); form.append('Title', title); form.append('Description', body); form.append('LatinCode', 'ldj3556'); // 直接传入原始File对象,无需额外处理 form.append('file', selectedFiles[i]); form.append('fileType', 'Warranty'); form.append('Id', rand); await TicketFileAPI.post( "/TicketFile", form, // 若API封装未自动处理请求头,需手动设置(Axios等库会自动生成,可省略此配置) { headers: { 'Content-Type': 'multipart/form-data' } } ); }
额外注意事项
- 确保
selectedFiles中的元素是标准File对象(一般来自<input type="file">的files属性)。 - 使用Axios等HTTP库时,无需手动设置
multipart/form-data请求头,库会自动根据FormData生成正确的请求头和分隔符。
内容的提问来源于stack exchange,提问作者abolfazl_mehdi
相关产品推荐
相关产品推荐

