在vue项目中,经常有图片上传的功能,类似微博的发表动态,都需要插入图片,其实我们需要做的就是两步:
1.获得本地图片,显示在页面;
2.上传图片到服务器
<div>
<div class="fl width-28per pos-relative" style="height: 80px;width: 80px">
<img src="static/img/test.png" class="width-100per border-rad-5">
<!--绑定src为了动态显示,v-show,当没有headimg的时候将这个图片坑隐藏-->
<img :src="headimg" class="width-100per border-rad-5" style="z-index: 98;position: absolute;top:0;left: 0;width: 80px;height: 80px;" v-show="has_headurl">
<input type="file" @change="getImgBase()" accept="image/*" style="position: absolute;top:0;left: 0;width: 100%;height: 100%;z-index: 99;opacity: 0">
</div>
input绑定change事件
getImgBase() {
this.headurl = ''
let event = event || window.event;
let file = event.target.files[0];
let reader = new FileReader();
//这个this指向的是vue
reader.vue = this
reader.readAsDataURL(file);
//在reader的load内部,this的指向是reader,所以使用自己的数据或者封装的vue方法,请使用this.vue.XXX
reader.onload = function () {
file.src = this.result
this.vue.headimg = file.src
//上传图片
let params =new FormData();
//formdata对象只能用append
params.append('token','xxxxxxxxxxxxx');
params.append('myfile',file)
console.log(params.get('myfile'))
let config = {
headers:{'Content-Type':'multipart/form-data'}
};
//这里用到的axios,需要在组件内部引入, import axios from 'axios',写在script下面第一个
axios.post('接口地址',params,config ).then(response=>{
console.log(response)
}
})
}
}