Vue.js 上传文件: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.value" :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>
当我点击按钮执行updateOneSection方法时,formData中并没有数据,请问问题出在哪? 根据您提供的代码,问题可能出在以下几个方面:
-
您在
updateOneSection方法中创建了一个空的FormData对象,然后将fileList中的每个文件添加到formData中。但是,您没有将formData传递给后端进行处理。请确保在updateOneSection方法中调用后端接口并将formData作为参数传递。 -
另外,请确保
fileList是通过ref创建的响应式数据。在handleChange方法中,您将fileList中的每个文件的status属性设置为'ready',然后将更新后的fileList重新赋值给fileList.value。这样做是正确的,但是请确保在模板中的:file-list="fileList"的绑定中使用fileList.value,而不是直接使用fileList。
请检查这些问题并根据需要进行更正。如果问题仍然存在,请提供更多详细信息,以便我能够更好地帮助您解决问题。
原文地址: https://www.cveoy.top/t/topic/qFHN 著作权归作者所有。请勿转载和采集!