<el-upload class="upload-demo" action="#" :file-list="fileList" :before-upload="uploadFile" :on-remove="handleRemove" multiple>
<el-button size="small" type="primary" style="margin-top: 10px">点击上传</el-button>
<div slot="tip" class="el-upload__tip">支持扩展名:.rar .zip .doc .docx .pdf .jpg .png
</div>
</el-upload>
upURL是上传成功之后调用的接口
uploadFile: function(file) {
var _this = this;
var len = file.name.split('.').length;
const isRightType = (file.name.split('.')[len - 1] === 'doc') || (file.name.split('.')[len - 1] === 'docx') ||
(file.name.split('.')[len - 1] === 'pdf') || (file.name.split('.')[len - 1] === 'rar') ||
(file.name.split('.')[len - 1] === 'zip') || (file.name.split('.')[len - 1] === 'jpg') ||
(file.name.split('.')[len - 1] === 'png');
const isLt2M = file.size / 1024 / 1024 < 2;
if (!isLt2M) {
this.$message.error('上传文件大小不能超过 2MB!');
return;
} else if (!isRightType) {
this.$message.error('上传文件的类型不正确!');
return;
} else { //可以上传
var fd = new FormData();
fd.append('file', file);
fd.append('businessType', 'file-type');
fd.append('businessId', file.uid);
// ajax请求
/*
ajax请求里面加上以下代码
*/
if (result.state == "0") {
_this.fileList.push({
name: '',
uid: fd.get('businessId')
});
delBugImg(_this.fileList, 'file-type', fd.get('businessId'));
_this.$message.error("上传失败的原因");
return
} else {
_this.$message('上传成功');
_this.fileList.push({
name: file.name,
url: upURL+"?fileId=" + result.id
});
}
}
},
/*
@handleRemove 删除已上传成功的附件
file.uid 附件的id
'file-type' 对应上传时写的'businessType'
*/
handleRemove: function(file, fileList) { //删除附件
delImg(fileList, 'file-type', file.uid, file.url.substring(file.url.indexOf("=") + 1, file.url.length));
},
下面是封装的js删除upload上传附件:
URL是与删除附件的接口
/*
URL :删除附件的接口
businessType:删除附件的类型
businessId:删除附件的id
fileList:上传的时候push到这个数组中
fileIds=file.uid, file.url.substring(file.url.indexOf("=") + 1, file.url.length)
*/
//删除有问题的附件
function delBugImg(fileList, businessType, businessId) {
$.ajax({
url: URL,
type: "get",
data: {
businessType: businessType,
businessId: businessId,
},
success: function(res) {
for (var i = 0; i < fileList.length; i++) {
if (fileList[i].uid == Number(businessId)) {
fileList.splice(i, 1);
}
}
}
})
}
//删除附件
function delImg(fileList, businessType, businessId, fileIds) {
$.ajax({
url: URL,
type: "get",
data: {
businessType: businessType,
businessId: businessId,
fileIds: fileIds
},
success: function(res) {
for (var i = 0; i < fileList.length; i++) {
var url = fileList[i].url;
if (url.indexOf(fileIds) != -1) {
fileList.splice(i, 1);
return;
}
}
}
})
}