React TypeScript中使用Axios多文件上传时无法读取FileList单个文件
React TypeScript中Axios多文件上传(带描述)的FormData处理问题
问题核心
使用Axios上传带描述字段的多文件时,直接将FileList对象添加到FormData,会导致数据被序列化为[object FileList],无法以二进制形式发送单个文件。
问题原因
FileList是浏览器提供的类数组对象,并非原生数组。直接将整个FileList传递给formData.append()时,会被当作普通对象处理,而不会解析其中的单个File实例。
解决方案
需要遍历FileList中的每个File对象,逐个添加到FormData中,同时关联对应的描述字段。此外,需修正接口定义以匹配实际的文件输入类型。
步骤1:修正接口定义
确保AttachmentDetail中的files字段类型匹配文件输入的返回值:
export interface AttachmentDetail { files: FileList | null; attachmentDetail: string; } export interface Attachments { id?: number; archiveid: number; file: Blob[] | undefined; attachmentDetail: AttachmentDetail[]; }
步骤2:修改文件上传逻辑
遍历每个附件项,再嵌套遍历FileList中的单个文件,将文件和对应的描述正确添加到FormData:
const addAttachments = (data: Attachments) => { const formData: FormData = new FormData(); data.attachmentDetail.forEach((detail, detailIndex) => { // 跳过空的FileList if (!detail.files) return; // 将FileList转为数组后遍历单个文件 Array.from(detail.files).forEach((file, fileIndex) => { // 添加文件,通过索引区分同一描述下的多个文件 formData.append(`Attachment[${detailIndex}][${fileIndex}]`, file); // 添加对应描述(可根据后端需求选择是否重复添加) formData.append(`Detail[${detailIndex}]`, detail.attachmentDetail); }); }); formData.append('ArchiveId', data.archiveid!.toString()); return axios.post<Attachments, any>('/AttachmentFile', formData, { // 无需手动设置Content-Type,Axios会自动生成带边界符的正确头信息 }); };
关键注意点
- 用
Array.from(detail.files)将FileList转换为数组,方便遍历操作 - 不要手动设置
multipart/form-data请求头,Axios会自动处理并添加正确的边界分隔符,手动设置可能导致后端无法解析数据 - 根据后端接收格式调整
FormData的键名(比如Attachment[${detailIndex}][${fileIndex}]可按需修改为后端期望的格式)
内容的提问来源于stack exchange,提问作者Mohammad Samim Safi
相关产品推荐
相关产品推荐

