vue中axios设置表单头_vue+axios表单中上传图片步骤详解
时间: 2023-07-24 18:07:25 浏览: 94
在Vue中使用axios上传图片需要设置请求头,这里提供一个简单的步骤:
1. 安装axios和qs库
```
npm install axios qs --save
```
2. 在vue组件中引入axios
```
import axios from 'axios';
```
3. 设置请求头
```
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
```
4. 创建FormData对象,设置上传的图片文件
```
let formData = new FormData();
formData.append('file', file);
```
5. 发送请求
```
axios.post(url, formData)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
```
完整代码如下:
```
<template>
<div>
<input type="file" ref="file" @change="uploadImage">
</div>
</template>
<script>
import axios from 'axios';
import qs from 'qs';
export default {
methods: {
uploadImage() {
let file = this.$refs.file.files[0];
let formData = new FormData();
formData.append('file', file);
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';
axios.post(url, formData)
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
}
}
}
</script>
```
阅读全文