1.文件上传
<div class="lefttext">
<h3>上传填好的商品资料表</h3>
<p style="margin: 10px 0px">
文件后缀名必须为xls 或xlsx ,文件大小不得大于50M
</p>
<a><el-upload
action="" //上传的地址
:on-remove="onRemove" //删除
:limit="3" //限制最大上传量
:http-request="changeFile" //自定义上传事件
:before-upload="beforeupload" //上传之前 可以做一些 文件格式/大小限制
:file-list="fileList"
>
<a v-show="isshow">点击上传</a>
</el-upload></a>
</div>
上传前的限制
//.上传前
beforeupload(file) {
console.log("上传前file", file);
//判断上传的类型
console.log(file);
if (!/\.(xlsx|xls)$/.test(file.name)) {
this.$notify.error({
title: "错误",
message: "上传文件只能为excel文件,且为xlsx,xls格式",
});
this.filelist = [];
return false;
} else {
//上传大小限制
const size = file.size / 1024 / 1024;
console.log("size", size);
if (size > 50) {
this.$notify.warning({
title: "警告",
message: "大小必须小于50M",
});
return;
} else {
this.isshow = false;
}
}
this.filename = file.name;
},
自定义上传事件
//上传
changeFile(file) {
//获取到要上传的文件
console.log('file',file);
//创建ForDate对象
let fd = new FormData();
//把上传文件的添加到 ForDate对象中
fd.append("file", file.file);
fd.append('module_address','oder') //定义需要上传其他参数
//请求接口
this.$axios({
url: "后端接口地址", //请求地址
method: "post", //请求方法
headers: { //请求头设置
"X-Requested-With": "XMLHttpRequest",
"Content-Type": "multipart/form-data",
"Access-Control-Allow-Origin": "*",
"Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
Authorization: `Bearer ${localStorage.getItem("token")}`, //携带的token
},
data: fd, //发送给后端的ForDate 文件
}).then((res) => {
console.log("res", res);
});
},
删除图片:由于提交给后端的图片,后端返回一个路径 比如:/storsage/attachmsent/oder/20230620/嘤s嘤s嘤-1687224751677649101afda579f.png
但是呢,组件提供的删除只会显示图片的原来信息,又不会跟后端返回的路径有什么相同的地方,就无法根据找相同点删除.
后端返回的结果
这是咱们删除输出的图片信息
说一下我的解决方法.
changeFile(file){
let fd = new FormData()
fd.append('file',file.file)
fd.append('module_address','oder')
this.$axios({
url:'/api/common/file/upload',
method:'post',
headers:{
'X-Requested-With': 'XMLHttpRequest',
'Content-Type': 'multipart/form-data',
'Access-Control-Allow-Origin': '*',
'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
'Authorization':`Bearer ${localStorage.getItem('token')}`
},
data:fd
}).then(res=>{
//记录上传的图片原始信息
this.originalimg.push(file.file) //这是上传成功后,把刚刚上传的图片信息保存起来.
this.imglist.push(res.data.data) //后端返回的数据 res.data.data 然后把它放在一个数组中
})
},
然后就是删除方法,就是拿this.originalimg 上传成功是保存的刚刚上传图片的信息, onRemove有俩参数(file,filelist) 第一个参数就是删除的图片信息 .第二个参数好像是删除后的图片数组(就是你上传传中的图片,不管是不是上传成功都会存在里面.,在我们这里点击后在filelist是不会显示file信息)
所以我们就需要拿到this.originalimg 遍历 和 file 相同的点,他们共同点就是uid,图片名称可能相同,大小也可能相同,但是uid是唯一的.然后根据判断就知道 i:坐标是多少,然后直接在后端返回的图片路径数组中删除对应的坐标.
onRemove(file) {
//删除图片
console.log('删除的时候',file);
console.log('this.originalimg',this.originalimg);
// //循环在提交成功后保存的 原始图片信息 , 对比删除的 图片信息 获取到图片的 坐标,如果删除图片 也要将后端返回的路径数组中对应的坐标删除
for(let i in this.originalimg){
console.log('originalimg',this.originalimg[i]);
if(this.originalimg[i].uid === file.uid){
//删除掉后端返回的对应图片信息
this.imglist.splice(i,1)
}
}
},