基于element plus的upload组件,主要功能是文件上传大小限制,重复上传限制,删除文件处理,我的接口是一个单独文件上传的接口,后端返回一个文件id,效果图和接口文档如下:


一、上传
template模块:
<el-upload
v-model:file-list="data.fileList"
class="upload-demo"
action="#"
:auto-upload="false"
:on-remove="handleRemove"
:before-remove="beforeRemove"
:on-change="filehandleChange"
style="width: 100%;"
>
<el-button type="primary" link :icon="UploadFilled">上传文件</el-button>
<template #tip>
<div class="el-upload__tip" style="color:red">注:单个上传文件不超过50M</div>
</template>
</el-upload>
js模块
<script setup>
const data = reactive({
fileList: [],
PrefileList: [], //先前的文件数组
fileSize: 50,
fileArr: []
)}
// 文件列表移除文件时的钩子
const handleRemove = (file) => {
// 4、删除文件时同时删除此文件已上传的文件id(此操作视具体情况)
data.originalArray.forEach((item,index) => {
if (item == file) {
data.fileArr.splice(index, 1)
form.gbqjxFjs = data.fileArr.join(",")
}
})
}
// 删除文件之前
const beforeRemove = (file, fileList) => {
// 3、先深拷贝一份原始数组
data.originalArray = Array.from(fileList)
return ElMessageBox.confirm(
`确定移除 ${file.name} ?`
).then(
() => true,
() => false
)
}
// 上传on-change事件
const filehandleChange = (file, fileList) => {
//1、判断文件大小是否合法,文件限制不能大于50M
const isLt5M = file.size / 1024 / 1024 < 50;
if (!isLt5M) {
ElMessage({
type: 'error',
message: '上传文件大小不能超过 50MB!',
})
fileList.splice(-1,1) //移除当前超出大小的文件
return false;
}
// 2、限制重复上传
// 将fileList去重后的长度如果小于目前数组的长度,说明有重复
const newListLength = new Set(fileList.map(item=>item.name)).size;
const listLength = fileList.length;
if(listLength > newListLength) {
ElMessage({
type: 'error',
message: '上传文件重复!',
})
fileList.splice(-1, 1) //移除当前重复的文件即末尾对象
return false;
}
//文件流是无法被序列化并传递的。new FormData()创建对象实例
let param = new FormData();
param.append('file', file.raw);
Fj(param).then(res => { //这里Fj是上传文件的api方法
data.fileArr.push(res.data.id)
form.gbqjxFjs = data.fileArr.join(",")
}).catch(err=>console.error('错误',err))
}
<script>
二、下载
效果图和接口文档和数据格式如图:


template模块
<template>
附件:
<div v-for="item in gbqjxFjs" :key="item.id">
<span @click="lookFj(item.id,item.fjmc + item.fjhz)">
//将文件名用a标签包裹
<a style="color:#65B5FF;cursor:pointer" download>
{{item.fjmc + item.fjhz}}
</a>
</span>
</div>
<template>
js模块
// 模拟接口数据
"gbqjxFjs": [
{
"id": "1654382306712727553",
"czsj": "2023-05-05 15:07:33",
"czrip": null,
"czrxm": null,
"czbmip": null,
"czbm": null,
"sfsc": "0",
"qjlb": "BING",
"fjdz": null,
"fjmc": "Git常用命令",
"dmbs": null,
"fjhz": ".md",
"fjdx": "91321",
"fjywbs": "1654383106520363009",
"ywb": null,
"fj": "IyBHSVTluLjnlKjlkb3ku6QNCg0KIyMg5YNCiAggDQoNCg==....."
}
]
// 查看附件
const lookFj = async (val, name) => {
let response = await fetch(下载文件接口地址);
let blob = await response.blob();
let objectUrl = window.URL.createObjectURL(blob);
let a = document.createElement('a');
a.href = objectUrl; //创建下载的链接
a.download = name;
a.click()
a.remove();
}
有问题,先看看接口和数据结构和我这是不是一样,请求头设为headers: {'Content-Type': 'multipart/form-data'}

6208

被折叠的 条评论
为什么被折叠?



