Vue.js el-upload 上传组件 FormData 文件丢失问题解决
<p>"这是我的前端代码:\n<script setup>\nimport {ref} from "vue";\n\nconst fileList = ref([])\n\nconst updateOneSection = async () => {\n const formData = new FormData()\n fileList.value.forEach(file => {\n formData.append("file", file.raw)\n })\n console.log(formData.getAll("file"))\n}\n\nconst handleChange = (file, fileList) => {\n fileList.forEach((file, index)=>{\n fileList[index].status = 'ready';\n })\n fileList.value = fileList\n console.log(fileList.value)\n}\n</script>\n\n<template>\n <div class="wrapper">\n <h2 class="formTitle">--块一</h2>\n <el-form>\n <el-upload\n :action="null"\n :auto-upload="false"\n :file-list="fileList"\n :on-change="handleChange"\n >\n <el-button type="primary">Click to upload</el-button>\n </el-upload>\n <el-form-item>\n <el-button type="primary" @click="updateOneSection">Submit</el-button>\n <el-button type="primary" @click="checkForm">Check</el-button>\n </el-form-item>\n </el-form>\n </div>\n</template>\n\n当我点击按钮调用updateOneSection方法时,我发现el-upload收集到的文件并没有被正确添加到formData中,请问问题出在哪\n内容:问题出在formData.append("file", file.raw)这一行代码中。在el-upload组件中,通过v-model绑定的fileList是一个数组,数组中的每个元素是一个对象,包含了文件的相关信息。而在updateOneSection方法中,你使用了fileList.value.forEach来遍历文件数组,然后将每个文件的原始数据通过formData.append方法添加到了formData中。但是,由于fileList是通过ref创建的响应式对象,它的value属性是一个数组,而不是一个普通的数组。因此,在遍历文件数组时,你需要使用fileList.value.forEach来访问数组的元素。修改updateOneSection方法如下:\n\nconst updateOneSection = async () => {\n const formData = new FormData()\n fileList.value.forEach(file => {\n formData.append("file", file.raw)\n })\n console.log(formData.getAll("file"))\n}\n</p>
原文地址: https://www.cveoy.top/t/topic/qFIu 著作权归作者所有。请勿转载和采集!