Vue 文件上传组件 FormData 数据为空问题解决方法
<script setup>
import {ref} from 'vue';
const fileList = ref([]);
const updateOneSection = async () => {
const formData = new FormData();
fileList.value.forEach(file => {
formData.append('file', file.raw);
});
console.log(formData);
};
const handleChange = (file, fileList) => {
fileList.forEach((file, index) => {
fileList[index].status = 'ready';
});
fileList.value = [...fileList];
console.log(fileList.value);
};
</script>
<template>
<div class="wrapper">
<h2 class="formTitle">--块一</h2>
<el-form>
<el-upload
:action="null"
:auto-upload="false"
:file-list="fileList"
:on-change="handleChange"
>
<el-button type="primary">Click to upload</el-button>
</el-upload>
<el-form-item>
<el-button type="primary" @click="updateOneSection">Submit</el-button>
<el-button type="primary" @click="checkForm">Check</el-button>
</el-form-item>
</el-form>
</div>
</template>
<p>当你点击按钮执行 updateOneSection 方法时,formData 中并没有数据,这是因为:</p>
<ol>
<li>
<p>在 handleChange 方法中,你使用了 <code>fileList.value = fileList</code> 来更新 fileList,这样做是不正确的。fileList 应该使用 ref 包裹,然后通过 fileList.value 来获取和更新其值。所以修改为 <code>fileList.value = fileList</code> 应该改为 <code>fileList.value = [...fileList]</code>。</p>
</li>
<li>
<p>在 updateOneSection 方法中,你使用了 <code>fileList.value.forEach(file => {formData.append("file", file.raw)})</code> 来循环遍历 fileList 并将文件添加到 formData 中。但是,fileList 是一个 ref 对象,你需要使用 <code>fileList.value</code> 来获取其实际值。所以修改为 <code>fileList.value.forEach(file => {formData.append("file", file.raw)})</code>。</p>
</li>
</ol>
<p>请尝试根据以上修改尝试解决问题。如果问题仍然存在,请提供更多关于问题的详细信息,以便我们可以更好地帮助你解决问题。</p>
原文地址: https://www.cveoy.top/t/topic/qFHK 著作权归作者所有。请勿转载和采集!