首先界面部分:直接上代码:
<template>
<el-form ref="form" :model="form">
<el-form-item label="栗子1" prop="eg1">
<el-upload
ref="upload"
action="#"
:http-request="uploadFile"
:before-upload="beforeUpload"
:auto-upload="true"
:limit="1"
:on-exceed="handleExceed">
<el-button size="small">
新增栗子1
<i class="el-icon-upload el-icon--right"></i>
</el-button>
<template slot-scope="scope">
<el-link>{{ scope.row.filePath }}</el-link>
</template>
</el-upload>
<el-button size="small" @click="handlePreview">预览</el-button>
<div v-if="previewImageUrl">
<img :src="previewImageUrl" style="max-width:100%">
</div>
</el-form-item>
</el-form>
</template>
前端页面代码,一个上传按钮,一个预览按钮,上传3个方法:上传前,上传限制,上传
回显一个按钮:handlePreview方法.
后端我是返回的图片的相对路径
上传的代码:
uploadFile() {
if (!this.attach) {
this.$message.warning("请先选择需要上传的文件!");
return;
}
let formData = new FormData();
formData.append("attachFile", this.attach);
console.log("上传附件在这里"+this.attach)
uploadAttach(formData).then((filePath) => {
this.form.eg1 = filePath; // 将文件路径直接赋值给组件属性
this.getList();
console.log(this.form.bianzhi+"打印下栗子1")
this.previewImageUrl = process.env.VUE_APP_BASE_API + filePath;
// 更新预览图片 URL
this.$message.success("附件上传成功!");
}).catch(() => {
this.$message.error("附件上传失败!")
});
this.$refs.upload.clearFiles();
},
url需要用
process.env.VUE_APP_BASE_API + filePath; // 更新预览图片 URL
如果是服务器绝对路径无需拼接了,直接url赋值进去ok
上传前加上传限制代码:
handleExceed(files, fileList) {
this.$message({
showClose: true,
message: `最多只能选择1个附件`,
type: `warning`
});
},
beforeUpload(file) {
this.attach = file;
let isLt10M = file.size / 1024 / 1024 < 20;
if (!isLt10M) {
this.$message.error("上传的附件大小不能超过20MB!")
}
return isLt10M;
},
最后是回显代码:
handlePreview() {
if (this.previewImageUrl) {
console.log(this.previewImageUrl+"看看显示的url对不对")
this.$alert(`<img src="${this.previewImageUrl}" width="100%">`, {
dangerouslyUseHTMLString: true,
callback: () => {}
});
} else {
console.log(this.previewImageUrl+"看看显示的url对不对")
this.$message.warning("没有上传文件!");
}
},
最后注意要在data里添加相对应的属性变量:
data() {
return {
showPreview: false,
previewImageUrl: '',
}
}