输入框:
<input
class="btn-upload"
type="file"
name="file"
accept="image/jpg, image/png, image/jpeg"
@change="$emit('handleInsertCapture',$event,item,'new')"
/>
input点击方法选择文件:并渲染到<img src>的src中
/**
* 新增图片
*/
handleInsertCapture($event, item,type) {
let file = $event.target.files[0];
if (!this.checkImg(file)) {
return;
}
const reader = new FileReader()
reader.onload = (e) => {
this.form.urlPath = e.target.result
}
reader.readAsDataURL(file)
this.file = file
},
图片校验:file:文件流 || 文件对象
/**
* 图片校验
*/
checkImg(file) {
const isJPG = file.type === "image/jpg";
const isJPEG = file.type === "image/jpeg";
const isPng = file.type === "image/png";
const isLt1M = file.size / 1024 / 1024 < 1;
if (!isJPG && !isPng && !isJPEG) {
this.$message.error("上传图片只能是 JPG/PNG 格式!");
return false;
}
if (!isLt1M) {
this.$message.error("上传图片大小不能超过 1M!");
return false;
}
return true;
},
图片上传:写在弹窗确认按钮上随便写个按钮触发你的接口就行。参数方式为:x-www-form-urlencoded所以用new FormData()了
let formData = new FormData();
formData.append("file", this.file);
上传接口xxx(formData).then(res=>{
if(res.code === 200){
this.$message.success('保存成功')
this.$emit('clear')
}
}).catch(err=>{
this.$message.error(err)
})