在vue 中用form-data和axios上传文件
时间: 2024-05-02 17:23:33 浏览: 20
对于这个问题,我可以给出回答。在vue中使用form-data和axios上传文件,你可以在组件中调用axios.post方法,将文件数据和其他表单数据传给后台。具体代码如下:
在template标签中定义一个表单元素:
```
<template>
<div>
<form @submit.prevent="submitForm">
<input type="file" v-model="fileData" />
<button type="submit">上传</button>
</form>
</div>
</template>
```
在script标签中定义submitForm方法,使用FormData实例将文件数据和其他表单数据一起传给后台。
```
<script>
import axios from 'axios'
export default {
data() {
return {
fileData: null, // 文件数据
formData: { // 其他表单数据
name: '',
age: ''
}
}
},
methods: {
async submitForm() {
const formData = new FormData()
formData.append('file', this.fileData)
formData.append('name', this.formData.name)
formData.append('age', this.formData.age)
const response = await axios.post('/api/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
console.log(response)
}
}
}
</script>
```
在这个例子中,我们使用了FormData实例将文件数据和其他表单数据一起传给后台,同时也设置了请求头的Content-Type为multipart/form-data.