https://blog.csdn.net/lijie627239856/article/details/79861957
绑定的事件是change,获取当前input元素,当前元素的files[0],就能获取上传的图片对象,所有属性为只读,如果上传图片不合适,可以把当前的value置为空字符串;
addfile(target){/*限制上传文件格式和大小*/
let iptobj=target.currentTarget;
/*匹配图片的格式*/
let img_regexp=/^image\/\w/g;
let notice_txt={txt:'上传文件不是图片!'};
/*如果上传的文件存在则进行判断处理*/
if(iptobj.files[0]){
if(!img_regexp.test(iptobj.files[0].type)){
iptobj.value='';
this.$store.commit('notifyfn',notice_txt);
}else{
if(iptobj.files[0].size>2*1024*1024){
iptobj.value='';
notice_txt.txt='上传图片不能超过2M!'
this.$store.commit('notifyfn',notice_txt);
}
}
};
}
2.读取图片文件传到后台:
submit_img(){/*读取图片信息*/
let el=this.$el;
let files=$(el).find('.add_file input')
let reader_arr=[];
this.company_imgdatas=[];/*清空存储图片base64信息的数组*/
files.each((index,item)=>{
/*遍历所有上传图片的input,每个input对应创建一个读取图片信息的FileReader对象*/
reader_arr.push(new FileReader());
/*如果input没有上传图片,就跳出循环,提示用户
* 如果上传了图片,则用对应的对象读取图片数据,并保存到company_imgdatas数组中;
* */
//console.log(reader_arr[]);
if(item.files[0]==undefined){
let notice_txt=$(item).parent().siblings('li').eq(0).text();
this.tag_notice(`${notice_txt}未提交`);
return false;
};
reader_arr[index].readAsDataURL(item.files[0]);
reader_arr[index].onload=(e)=>{
console.log(e.target.result);
this.company_imgdatas.push(e.target.result)
}
})
}