还是先看效果图,点击选择就自动触发事件了,不用再点上传
其实代码挺简单的:
先是写了一个img一个input,然后把input隐藏掉(visibility: hidden,display是直接不加载要注意),然后图片点击事件时重写input的click事件,然后使用监听当input的值发生改变时,change触发上传事件。就ok了
本地图片不显示的话就qualificationCertificateImage:”require('../../assets/image/uploading.jpg')
uploadFile方法我用了一个Promise函数,有兴趣的话可以了解其特性。
<template>
<div>
<div class="container">
<div class="c-card-ico">
<img src="../../static/images/qualificationCertificateImage.png"/>
<img :src=qualificationCertificateImage @click="clp()"/><br/>
<input type="file" id="qualificationCertificateImage"/><br/>
</div>
<div class="c-card-ico">
<img src="../../static/images/handPhotoUrl.png"/>
<img :src=handPhotoUrl @click="clp1()"/><br/>
<input type="file" id="handPhotoUrl"/><br/>
</div>
</div>
</div>
</template>
<script>
export default {
name: "MobilesInvite",
data(){
return{
qualificationCertificateImage:
'../../static/images/qualificationCertificateImage.png'
handPhotoUrl:'../../static/images/qualificationCertificateImage.png'
}
},
methods:{
clp(){
return document.getElementById("qualificationCertificateImage").click();
},
clp1(){
return document.getElementById("handPhotoUrl").click();
},
uploadFile(that){
return new Promise((resolve, reject) => {
if(document.getElementById(that).val() != ""){
var f3 = that.files;
var str3 =f3[0]
let formData = new FormData();
formData.append('images', str3);
let config = {
headers: {
'token': sessionStorage.getItem('token') //设置token 其中K名要和后端协调好
},
};
this.$axios.post(this.GLOBAL.baseURL+'/oss/uploadFile',formData,config).then(response=>{
resolve(response.data)
}).catch(err => {
reject(err)
})
}
})
}
},
mounted(){
let that = this, $qualificationCertificateImage = document.getElementById("#qualificationCertificateImage"),
$handPhotoUrl = document.getElementById("#handPhotoUrl"),that = this;
// ①为input设定change事件
$qualificationCertificateImage.change(function () {
// ②如果value不为空,调用文件加载方法
that.uploadFile(this).then(res=>{
that.qualificationCertificateImage = res.data.image0
});
});
$handPhotoUrl.change(function () {
that.uploadFile(this).then(res=>{
that.handPhotoUrl = res.data.image0
});
});
},
}
</script>
<style lang="less" scoped>
.container{
.c-card-ico{
margin-top: 10px;
img{
width: 150px;
height: 100px;
}
input{
visibility: hidden;
/*或者display: none;看你需求*/
}
}
}
</style>
想要好看的话就发挥想象力去写样式哦,顺带一提,vue的获取dom相对简单
使用ref就可以,其他的步骤跟原生的差不多
<img :src=qualificationCertificateImage @click="clp()"/>
<input type="file" @input="con" ref="accountCertificateImg"/>
clp(){
return this.$refs.accountCertificateImg.click();
},
con(e){
this.uploadFile(e.target.files[0]).then(res=>{console.log(res)})
},
uploadFile(img){
return new Promise((resolve, reject) => {
let formData = new FormData();
formData.append('images', img);
let config = {
headers: {
'token': this.token
},
};
this.$axios.post(this.GLOBAL.baseURL+'/tiantue/public/oss/uploadFile',formData,config).then(response=>{
resolve(response.data)
}).catch(err => {
reject(err)
})
})
}