首先看一下官方文档,el-upload有很多参数和方法,具体请查看对应文档。https://element.eleme.cn/#/zh-CN/component/upload
首先需求如下,需要做多文件上传,且需要预览上传图片,查看upload控件,只有list-type="picture-card"这种方式最合适。
在做的过程中有几个点需要注意:
- 上传完成之后图片要获取到对应的图片网址
- 上传完成之后允许用户删除对应的图片
基于上面两点要求,开始做编码准备,第一版代码如下:
<el-upload :http-request="uploadImageH"
list-type="picture-card"
:before-upload="beforeUploadH"
:on-preview="handlePictureCardPreview"
:auto-upload="true"
:file-list="ImgsHorizontal"
:on-success="handleSuccessH"
:on-remove="handleRemoveH">
<i class="el-icon-plus"></i>
</el-upload>
var container = new Vue({
el: '.page-content',
data: {
ImgsHorizontal: [],//横屏上传组件的图片对象列表
UrlImgsHList: [],//横屏图片上传之后的URL LIST
dialogImageUrl: "",
dialogVisible: false,
},
method:{
//上传图片之前对图片进行检查
beforeUploadH(file) {
var fileExtension = file.name.substring(file.name.lastIndexOf(".")).toLowerCase();
if (fileExtension != ".png" && fileExtension != ".jpg" && fileExtension != ".jpeg") {
this.$message({ message: '截图文件仅支持png,jpg格式', type: 'warning' });
this.ImgsHorizontal = [];
return;
}
this.imageData.file = file;
this.imageData.fileName = file.name
},
//上传成功的处理事件
handleSuccessH: function (res, file) {
this.ImgsHorizontal.push(file);
},
//预览图片大图
handlePictureCardPreview(file) {
this.dialogImageUrl = file.url;
this.dialogVisible = true;
},
//移除横屏图片列表
handleRemoveH: function (file, filelist) {
//{"status":"success","name":"5.jpg","size":385863,"percentage":0,"uid":1759054158738,"raw":{"uid":1759054158738},"url":"blob:http://localhost:8102/71e4a263-70c9-4b9d-bfe2-bfdd06897afc"}
//分析上传对象,发现UID为唯一,通过UID在UrlImgsHList中进行index查找删除,因为提交的时候要确保图片和网址一一对应
var index = this.ImgsHorizontal.findIndex(t => t.uid === file.uid);
this.UrlImgsHList.splice(index);
this.ImgsHorizontal.splice(index);
},
//上传横屏截图
uploadImageH: function (file) {
var that = this;
var data = new FormData()
data.append('file', this.imageData.file);
data.append('fileName', this.imageData.fileName);
const token = Cookies.get('access_token');
const users = Cookies.get("UserInfo");
// 创建请求的配置对象,用于后台校验身份和Token验证
const config = {
headers: {
'token': token,
'user': users
}
};
axios.post('/File/UploadScreenshot', data, config).
then(function (res) {
if (res.data.Code === 0) {
that.UrlImgsHList.push(res.data.Data);
}
else {
that.$alert(res.data.Msg, '提示消息');
}
}).catch(function (error) {
console.error(error);
});
},
}
});
但是执行完成上述代码,发现最重要的handleSuccessH没有执行,查询资料,有说action的原生方法被http-request覆盖,需要手动触发onsuccess方法,修改过后也不行。
后面在统一修改后台请求为异步的时候,发现,将方法uploadImageH修改为异步方法之后,组件的on-success方法就能正常执行,也满足了逻辑要求。
1051

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



