记录一个图片上传的功能,满足只能上传一张图片,并且可以需要判断上传图片是否为png,且大小不能超过2MB,除此之外,先上传图片,再点击提交按钮提交图片。
这里用的iview的Upload组件,其实element一样。
目录
template
<div class="demo-upload-list" v-for="item in uploadList">
<template v-show="item.status === 'finished'">
<img :src="imgUrl" />
<div class="demo-upload-list-cover">
<Icon type="ios-eye-outline" @click.native="handleView(item)"></Icon>
<Icon type="ios-trash-outline" @click.native="handleRemove(item)"></Icon>
</div>
</template>
</div>
<Upload
class="upload-item"
ref="upload"
:show-upload-list="false"
accept="png"
:before-upload="handleBeforeUpload"
multiple
type="drag"
action="#"
>
<div class="uploadTitle">
<Icon type="ios-cloud-upload" size="52" style="color: #8345b8"></Icon>
<p>png 文件不得超过 2MB,建议1300*300像素</p>
</div>
</Upload>
<Modal title="查看登录页logo" v-model="visible">
<div style="background: #000">
<img :src="imgUrl" v-if="visible" style="width: 100%" />
</div>
</Modal>
js
获取图片
mounted() {
this.getResult();
this.uploadList = this.$refs.upload.fileList;
},
限制图片上传大小与格式
handleFormatError(file) {
if (file.type.indexOf("png") > -1) {
return true;
} else {
this.$Notice.warning({
title: "文件格式不正确",
desc:
"文件名为 " + file.name + "的格式不符合要求,请选择png图片上传.",
});
return false;
}
},
handleMaxSize(file) {
// 限制上传文件的大小
const isLt = file.size * 1 > 1024 * 2 * 1024 ? false : true;
if (!isLt) {
this.$Notice.warning({
title: "超出文件上传大小限制",
desc:
"文件名为 " +
file.name +
" 的图片大小超出限制,请上传小于2MB的文件",
});
return false;
} else {
return true;
}
},
上传图片
handleBeforeUpload(file) {
//也可以上传多张,修改下面的数字再加其他限制即可
const check = this.uploadList1.length < 1;
if (!check) {
this.$Notice.warning({
title: "当前图片已存在,请删除当前图片后重新上传.",
});
} else if (this.handleFormatError(file) && this.handleMaxSize(file)) {
//展示图片
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
const _base64 = reader.result;
file.url = _base64;
this.imgUrl = file.url;
};
this.uploadList[0].status = "start";
this.uploadList.pop();//删除现在的图片保存数组
this.uploadFile = file;
file.status = "finished";//修改状态,也可以不加,只是为了控制展示
this.formData = new FormData();
this.formData.append("file", file);
//这里接口需要什么都可以append()什么
this.uploadList.push(file);
}
return false;
},
这里用的是 before-upload方法,也可以用其他方法,如果是用这个方法,需要返回值,具体看官网。
查看与删除图片
handleView(item) {
this.imgUrl = item.url;
this.visible = true;
},
handleRemove(file) {
const fileList = this.uploadList;
this.uploadList.splice(fileList.indexOf(file), 1);
},
补充:提交图片
//提交修改
async handleSubmit() {
if (this.formData) {
let res = await this.axios.post(
"url",
this.formData
);
if (res) {
this.uploadList = [];
}
}
this.systemItemModal = false;
this.uploadList = [];
this.uploadList.pop();
},
效果如图: