<input type="file" accept="image/png,image/gif,image/jpeg"
@change="uploadImg($event)"/>
methods: 中方法如下
uploadImg (e) {
let file = e.target.files[0]
let param = new FormData() // 创建form对象
param.append('file', file, file.name)// 通过append向form对象添加数据
param.append('chunk', '0')// 添加form表单中其他数据
console.log(param.get('file')) // FormData私有类对象,访问不到,可以通过get判断值是否传进去
let config = {
headers: {'Content-Type': 'multipart/form-data'}
} // 添加请求头
this.$request('post', '/common/upload', param, config)
.then(response => {
console.log(response.data)
})
}
npm install axios -save // 安装axios
http.js中
import axios from 'axios'
var instance = axios.create({
headers: {
'Content-Type': 'application/json'
},
timeout: 5000,
// baseURL: 'https://api.uyuexing.cn/'
baseURL: 'https://dev.api.youyueting.cn/'
})
function request (methed, url, data = {}, headers) {
return new Promise((resolve, reject) => {
instance({
method: methed || 'post',
url: url,
data: methed === 'get' ? { params: data } : data,
headers: headers || { 'Content-Type': 'application/json' }
})
.then(response => {
// 对接口错误码做处理
resolve(response.data)
})
.catch(err => {
reject(err)
})
})
}