Element-Plus el-upload 提供了非常方便快捷的图片上传功能,点击或者拖拽上传文件,展示图片缩略图并提供放大镜,下载和删除功能。
官方网站:https://element-plus.org/zh-CN/component/upload.html
效果展示:
效果图一:
未上传图片效果。
效果图二:
点击+加号上传图片后展示缩略图效果。
效果图三:
鼠标移入缩略图图片中出现放大镜、下载和删除工具。
效果图四:
点击放大镜展示预览图片对话框。
代码展示:
图片上传:
<!-- action: 上传图片服务器接口路径
list-type: 文件列表的类型
file-list: 上传文件列表
auto-upload: 自动上传
headers: 设置上传的请求头
on-success: 上传成功的回调函数-->
<el-upload action="/api/file/upload" list-type="picture-card" v-model:file-list="fileList"
:auto-upload="true" :headers="{'Authorization':token}" :on-success="uploadSuccess">
<el-icon>
<Plus />
</el-icon>
<template #file="{ file }">
<div>
<img class="el-upload-list__item-thumbnail" :src="file.url" alt="" />
<span class="el-upload-list__item-actions">
<!-- 图片预览 -->
<span class="el-upload-list__item-preview"
@click="handlePictureCardPreview(file)">
<el-icon><zoom-in /></el-icon>
</span>
<span class="el-upload-list__item-delete" @click="handleDownload(file)">
<el-icon>
<Download />
</el-icon>
</span>
<span class="el-upload-list__item-delete"
@click="handleRemove(file,fileList)">
<el-icon>
<Delete />
</el-icon>
</span>
</span>
</div>
</template>
</el-upload>
图片预览:
<!-- 预览图片 -->
<el-dialog v-model="dialogVisible" width="435px">
<img w-full :src="dialogImageUrl" width="400px" alt="预览图片" />
</el-dialog>
下载图片JS代码:
如何通过JS代码下载图片?
1. 获取图片URL
2. 创建<a>标签设置href为图片的URL
3. 设置download属性为文件名,指定下载时图片的名称
4. <a>标签触发下载
5. 清理DOM,移除不再需要的元素
const handleDownload = (file : UploadFile) => {
const link = document.createElement('a');
link.href = file.url;
link.download = file.name;
document.body.appendChild(link);
link.click(); // 模拟点击
document.body.removeChild(link); // 下载后移除元素
}
预览图片JS代码:
// 预览图片
const handlePictureCardPreview = (file : UploadFile) => {
dialogImageUrl.value = file.url!
dialogVisible.value = true;
};
删除图片JS代码:
循环图片列表,找出与被删除图片相同name的图片下标进行删除。
// 删除图片
const handleRemove = (file, fileList) => {
for (let i = 0; i < fileList.length; i++) {
if (fileList[i].name == file.name) {
fileList.splice(i, 1);
}
}
}
上传图片成功回调函数:
const uploadSuccess = ({ data }) => {
console.log(data);
// 上传成功后将回调函数返回的图片地址信息存入到数据库中
changeArticleInfo.value.coverImg = data;
console.dir(changeArticleInfo.value)
ElMessage.success('上传成功');
}