Element ui 实现上传附件功能
el-upload
其中:
action //必要属性,上传文件的地址,可以不给,但必须要有,不给就i调接口上传
:http-request="uploadFile"//这个是就上传文件的方法,把上传的接口写在这个方法里
ref="upload"
:limit="fileLimit"//上传文件个数的限制
:on-remove="handleRemove"//上传之后,移除的事件
:file-list="fileList"//上传了那些文件的列表
:on-exceed="handleExceed"//超出上传文件个数的错误回调
:before-upload="beforeUpload"//文件通过接口上传之前,一般用来判断规则,
//比如文件大小,文件类型
:show-file-list="false"//是否用默认文件列表显示
:headers="headers"//上传文件的请求头
data:
methods:
methods: {
//上传文件之前
beforeUpload(file){
if (file.type != "" || file.type != null || file.type != undefined){
//截取文件的后缀,判断文件类型
const FileExt = file.name.replace(/.+\./, "").toLowerCase();
//计算文件的大小
const isLt5M = file.size / 1024 / 1024 < 50; //这里做文件大小限制
//如果大于50M
if (!isLt5M) {
this.$showMessage('上传文件大小不能超过 50MB!');
return false;
}
//如果文件类型不在允许上传的范围内
if(this.fileType.includes(FileExt)){
return true;
}
else {
this.$message.error("上传文件格式不正确!");
return false;
}
}
},
//上传了的文件给移除的事件,由于没有用到默认的展示,所以没有用到
handleRemove(){
},
//这是自定义的移除事件
handleClose(i){
this.fileList.splice(i,1);//删除上传的文件
if(this.fileList.length == 0){//如果删完了
this.fileflag = true;//显示url必填的标识
this.$set(this.rules.url,0,{ required: true, validator: this.validatorUrl, trigger: 'blur' })//然后动态的添加本地方法的校验规则
}
},
//超出文件个数的回调
handleExceed(){
this.$message({
type:'warning',
message:'超出最大上传文件数量的限制!'
});return
},
//上传文件的事件
uploadFile(item){
this.$showMessage('文件上传中........')
//上传文件的需要formdata类型;所以要转
let FormDatas = new FormData()
FormDatas.append('file',item.file);
this.$axios({
method: 'post',
url: '/file/fileUpload',
headers:this.headers,
timeout: 30000,
data: FormDatas
}).then(res=>{
if(res.data.id != '' || res.data.id != null){
this.fileList.push(item.file);//成功过后手动将文件添加到展示列表里
let i = this.fileList.indexOf(item.file)
this.fileList[i].id = res.data.id;//id也添加进去,最后整个大表单提交的时候需要的
if(this.fileList.length > 0){//如果上传了附件就把校验规则给干掉
this.fileflag = false;
this.$set(this.rules.url,0,'')
}
//this.handleSuccess();
}
})
},
//上传成功后的回调
handleSuccess(){
},