首先得有一个控件用来选择文件
<input type="file" accept="image/*" @change="fileChanged" ref="file">
也可以隐藏file控件然后用其他事件触发file控件的chagne事件
this.files = this.$refs.file.files //将控件的值赋值给成员变量,可以不用
const formData = new FormData()
formData.append("file0", this.files[0].file)//注意一定要.file。。。不然this.file[0]只是一个元素,真正的file在元素里面,是一个叫做file的对象
const xhr = new XMLHttpRequest()xhr.open('POST','server url', true) //server url自行填充,true代表异步
//发送完之后执行的函数还有其他接口可以设置比如timeout、error
xhr.onload = () => {const response=JSON.parse(xhr.response)//response就是服务器返回的信息
}
xhr.send(formData)//执行发送指令
//普通的post请求
//初始化post数据
let postData = this.$qs.stringify({
action:"getinfo",
userID:localStorage.getItem('user_id'),
token:localStorage.getItem('token')
})
//qs的使用需要import qs from 'qs';
//qs的使用需要Vue.prototype.$qs = qs;
//执行post
this.axios({
method:'post',
url:'server url', //server url自行填充
data:postData
}).then(res=>{
if(0 == res.data.statusCode){//服务器返回的字段,代表返回值
localStorage.setItem('userinfo', res.data.userinfo)//服务器返回的字段,代表返回信息
}
else {
console.log('error' + res.data.statusCode)
}}).catch(error=>{
console.log('访问服务器失败')
console.log(error)
})
//另外记录一个proxyTable的问题
proxyTable: {
'/api': {
target:'http://192.168.0.121'
changeOrigin: true,
pathRewrite: {
'^/api': '/'
}
},
。。。
}
本来直接修改vue文件可以立即生效,但是修改proxyTable后没有立即生效,以为出bug,后来结束掉npm run dev,再次npm run dev就ok了