elementUI之upload上传、预览、删除(带确认提示)
效果入下:
1.el-upload的HTML部分
1) action="#"
属性用于控制【上传地址,是必选项】,但是这里我们不使用,所以复制“#”。这是因为一般在项目开发中,我们的接口请求一般习惯于统一管理,我们会在后续的代码中使用axios上传。
2)accept=".pdf"
属性标识上传的文件类型,多个类型可用【英文逗号】分隔。
3)multiple
属性控制【可以同时传递多个文件】。
4)limit="3"
属性控制【最多上传的文件数量】
5):file-list="fileList"
属性是【上传后的文件列表展示】
6):auto-upload="false"
属性【阻止自动上传】,建议阻止自动上传
<el-upload
class="upload-demo"
action="#"
accept=".pdf"
:on-preview="handlePreview"
:before-remove="beforeRemove"
:on-exceed="handleExceed"
:on-change="uploadCertificateChange"
multiple
:limit="3"
:file-list="fileList"
:auto-upload="false"
>
<el-button
size="small"
type="primary"
v-loading.fullscreen.lock="fullscreenLoading"
>点击上传</el-button
>
<div slot="tip" class="el-upload__tip">只能上传PDF文件</div>
</el-upload>
2.JS代码
1)上传
on-change
文件状态改变时的钩子,添加文件、上传成功和上传失败时都会被调用
uploadCertificateChange(file) {
this.$confirm("上传文件,是否继续?", "提示")
.then(() => {
this.fullscreenLoading = true;
let fd = new FormData();
fd.append("files", file.raw);
this.$cm
.postUploadCertificate(fd)
.then((res) => {
console.log(res);
if (res.ErrorCode == "00000000") {
this.$message.success("上传成功");
this.certificatePath = res.Response;
} else {
this.$message.warning(res.Message);
this.fileList.pop();
}
this.fullscreenLoading = false;
})
.catch((err) => {
this.fullscreenLoading = false;
err && this.$message.warning(err);
});
return true;
})
.catch(() => {
this.$message.success("取消成功");
this.fileList = [];
return false;
});
},
2)预览
on-preview
是点击文件列表中已上传的文件时的钩子,用于实现预览
handlePreview(file) {
// axios的基地址和上传文件路径同时存在时可预览
if (this.$axios.defaults.baseURL && this.certificatePath) {
window.open(
this.$axios.defaults.baseURL + this.certificatePath,
"_blank"
);
} else {
this.$message.warning("暂不支持预览");
}
},
3)删除
before-remove
删除文件之前的钩子,参数为上传的文件和文件列表,若返回 false 或者返回 Promise 且被 reject,则停止删除
beforeRemove(file, fileList) {
// 移除前
return this.$confirm(`确定移除 ${
file.name}?`).then(() => {
this.$message.success("已移除");
this.certificatePath = "";
});
},
4)超出规定的文件上传个数限定
on-exceed
文件超出个数限制时的钩子
handleExceed(files, fileList) {
this.$message.warning(
`当前限制选择 3 个文件,本次选择了 ${
files.length} 个文件,已上传了 ${
fileList.length} 个文件`
);
},