vue post请求file
时间: 2023-06-25 14:08:01 浏览: 100
要在Vue中使用POST请求上传文件,你需要使用FormData对象和axios库。
首先,创建一个FormData对象,并向其添加要上传的文件。假设你有一个input元素用于选择文件:
```html
<input type="file" @change="onFileChange">
```
然后,在Vue组件的methods中定义onFileChange方法,该方法将选定的文件添加到FormData对象中:
```javascript
methods: {
onFileChange(event) {
const file = event.target.files[0];
this.formdata = new FormData();
this.formdata.append('file', file);
},
submitForm() {
axios.post('/api/upload', this.formdata)
.then(response => {
console.log(response.data);
})
.catch(error => {
console.log(error.response.data);
});
}
}
```
在submitForm方法中,你可以使用axios库进行POST请求并将FormData对象作为数据发送。服务器端需要对上传的文件进行处理,并将结果返回给客户端。
注意:在提交表单前,你可能需要验证选择的文件是否符合要求,例如文件类型、大小等。
阅读全文
相关推荐

















