elementui formdata
使用 ElementUI 上传文件并处理 FormData
ElementUI 的 el-upload 组件可以方便地实现文件上传功能,结合 FormData 可以处理文件和其他表单数据。
安装 ElementUI
确保项目中已安装 ElementUI,可以通过 npm 或 yarn 安装:

npm install element-ui
基本文件上传示例
在 Vue 组件中使用 el-upload 上传文件:

<template>
<el-upload
action="/api/upload"
:on-success="handleSuccess"
:before-upload="beforeUpload"
:data="formData">
<el-button type="primary">点击上传</el-button>
</el-upload>
</template>
<script>
export default {
data() {
return {
formData: {
userId: 123,
token: 'your-token'
}
}
},
methods: {
beforeUpload(file) {
const isJPG = file.type === 'image/jpeg'
if (!isJPG) {
this.$message.error('只能上传 JPG 图片!')
return false
}
return true
},
handleSuccess(response, file) {
this.$message.success('上传成功!')
}
}
}
</script>
手动构建 FormData
如果需要手动构建 FormData 并发送请求:
<template>
<el-upload
:auto-upload="false"
:on-change="handleChange"
ref="upload">
<el-button type="primary">选择文件</el-button>
<el-button @click="submitUpload">上传</el-button>
</el-upload>
</template>
<script>
export default {
methods: {
handleChange(file) {
this.file = file
},
submitUpload() {
const formData = new FormData()
formData.append('file', this.file.raw)
formData.append('userId', 123)
this.$axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
}).then(response => {
this.$message.success('上传成功!')
})
}
}
}
</script>
处理多个文件上传
使用 multiple 属性允许选择多个文件:
<template>
<el-upload
multiple
:auto-upload="false"
:on-change="handleChange"
ref="upload">
<el-button type="primary">选择多个文件</el-button>
<el-button @click="submitUpload">上传</el-button>
</el-upload>
</template>
<script>
export default {
methods: {
handleChange(file, fileList) {
this.fileList = fileList
},
submitUpload() {
const formData = new FormData()
this.fileList.forEach(file => {
formData.append('files[]', file.raw)
})
formData.append('userId', 123)
this.$axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
}
}
}
</script>
注意事项
- 使用
FormData时,确保设置正确的Content-Type为multipart/form-data el-upload的auto-upload属性控制是否自动上传- 文件对象存储在
file.raw中,而不是file本身 - 服务器端需要正确处理
multipart/form-data格式的请求






