一。需求
用户可以选择图片,并回显出来,给按钮注册点击事件上传图片和文字参数。
二。代码
1.隐藏 file 输入框
2.将 选择图片框 上的注册事件 绑定带 file 文件框上
<div class="uploaditem">
<p>添加图片</p>
<!--照片区域-->
<div class="picarea" v-for="(urls, index) in imgs " :key="index">
<div class="delete" v-on:click="deleteImg(index)"><i class="icon iconashanchu"></i>
</div>
<img :src="urls" width="100px" height="100px" />
</div>
<div class="addpic" @click="imgClick()"><img src="../../assets/add.png" alt=""></div>
<input type="file" id='uploadFile' name="img" accept="image/*" v-on:change="readLocalFile()">
</div>
<mt-button type="primary" size="large" @click.native="submitPic"><i class="icon iconaok" slot="icon"></i>发表</mt-button>
3.获取file框的图片信息,创建filereader 对象 利用files属性 其余的可以自行百度FileReader属性
methods:{
deleteImg(index){
this.imgs.splice(index,1)
},
imgClick(){
document.getElementById("uploadFile").click()
},
readLocalFile(){
var localFile = document.getElementById("uploadFile").files[0];
var reader = new FileReader();
var content;
var current = this;
reader.onload = function(event){
content = event.target.result;
current.imgs.push(content)
}
reader.onerror = function(event){
alert('error')
}
content = reader.readAsDataURL(localFile,"UTF-8");
var sss = document.getElementById("uploadFile").value;
console.log('sss'+sss)
},
submitPic(){
var localFile = document.getElementById("uploadFile").files[0];
let params = new FormData()
params.append("title",this.title)
params.append("content",this.content)
params.append("mFileArr",localFile,localFile.name)
this.axios.post(url,params,{
headers:{
'Content-Type':'multipart/form-data'
},
withCredentials: true
}).then(res => {
console.log(res)
})
}
}