Vue文件上传组件文件名获取问题及解决方案
问题背景
在Vue项目中,自定义文件上传组件SecureFileUpload通过v-model绑定文件URL列表,但无法获取上传文件的原始文件名,导致提交表单时文件名信息丢失。
问题分析
- 单向数据流限制:组件只通过
valueprop接收URL,通过input事件传递URL列表,没有传递文件名的机制。 - 缺少文件名绑定:父组件定义了
fileName字段,但未与子组件建立有效绑定。 - 事件机制不完整:子组件只触发
input事件更新URL,没有更新文件名的事件。
解决方案
1. 添加fileName prop
props: {
// 文件URL
value: [String, Object, Array],
// 文件名
fileName: [String, Array],
}
2. 添加fileName watcher
watch: {
fileName: {
handler(val) {
if (val && this.fileList.length > 0) {
const nameList = Array.isArray(val) ? val : val.split(",");
this.fileList.forEach((file, index) => {
if (nameList[index]) {
file.name = nameList[index];
}
});
}
},
deep: true,
immediate: true,
}
}
3. 修改uploadedSuccessfully方法
uploadedSuccessfully() {
if (this.number > 0 && this.uploadList.length === this.number) {
this.fileList = this.fileList.concat(this.uploadList);
this.uploadList = [];
this.number = 0;
this.$emit("input", this.listToString(this.fileList));
// 提取文件名并触发fileName事件
const fileNames = this.fileList.map(file => file.name);
this.$emit("update:fileName", fileNames);
this.$modal.closeLoading();
}
}
4. 修改父组件使用方式
<secure-file-upload
v-model="form.fileUrl"
:file-name.sync="form.fileName"
:fileSize="1024"
:fileType="[...]">
</secure-file-upload>
总结
通过以上修改,文件上传组件能够同时维护文件URL和文件名两个列表,并通过不同的事件将它们传递给父组件,确保了数据的完整性。现在,当用户上传文件时,我们不仅能获得文件的访问地址,还能获得文件的原始名称,提升了用户体验和数据管理的准确性。
评论区