如何在Angular FormControl表单中实现多文件上传?当前仅能获取首张选中图片
问题原因
你的代码存在以下几个核心错误:
- 仅读取了文件列表的第一个文件:
const file = files!.files![0]只获取了选中文件中下标为0的第一个文件,剩下2个选中的文件完全没有被处理 - 文件输入框未开启多选:如果你的
<input type="file">没有加multiple属性,本身就只能选中单个文件,无法同时选择3张图片 - Promise调用逻辑错误:你用逗号分隔3个Promise调用,仅最后一个
getPic3(file)的.then回调会生效,且3个方法都传入了同一个第一个文件,就算执行成功3个pic字段存的也都是同一张图的内容 - 重复冗余的方法定义:
getData、getPic2、getPic3三个方法功能完全一致,属于冗余代码不需要重复定义 - 响应式表单赋值不规范:直接修改
surveyForm.value不符合Angular响应式表单的使用规范,应该用patchValue/setValue方法赋值
修复方案
- 首先修改HTML中的文件上传控件,添加
multiple属性支持多选:
<input type="file" id="customFile" accept="image/jpeg" multiple>
- 删除冗余的
getPic2、getPic3方法,只保留通用的getData方法 - 重写
onSubmit方法,批量读取选中的3个文件,全部读取完成后再提交表单:
async onSubmit() { const customFile = document.getElementById("customFile") as HTMLInputElement; const files = customFile.files; // 先校验是否选了3个文件 if (!files || files.length !== 3) { alert("请选择3张JPEG图片"); return; } try { // 批量读取3个文件 const [pic1, pic2, pic3] = await Promise.all([ this.getData(files[0]), this.getData(files[1]), this.getData(files[2]) ]); // 正确给响应式表单赋值 this.surveyForm.patchValue({ pic1, pic2, pic3 }); // 提交表单 this.userService.addSurveyRes( this.surveyForm.value.ques1, this.surveyForm.value.selectedOpt, pic1, pic2, pic3 ).subscribe(results => { alert("Thank you for your response."); location.reload(); }); } catch (e) { console.error("图片读取失败", e); alert("图片读取失败,请重新选择"); } }
内容的提问来源于stack exchange,提问作者artyom
相关产品推荐
相关产品推荐

