element上传附件(el-upload 超详细)
经常会有人问我上传文件怎么做,这个功能其实比较常见的功能,后台管理系统基本上都有,这就离不开element的el-upload,虽然配置项很多,我们慢慢看,先看结构代码,之中有注释:
<div class="flex-div uploaditem"> //这里是上传了那些文件的提示,我没有要默认的文件提示 <el-tooltip class="item" effect="dark" :content="tag.name" placement="top-start" v-for="(tag,index) in fileList" :key="index"> <el-tag style="margin-right:10px;display:flex;" :disable-transitions="false" @close="handleClose(index)" closable @click="downloadFile(tag)"><i class="el-icon-paperclip"></i><span class="tagtext">{{tag.name}}</span></el-tag> </el-tooltip> <el-upload class="upload-demo" 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"//上传文件的请求头 > <!-- action="/api/file/fileUpload" --> <el-button class="btn"><i class="el-icon-paperclip"></i>上传附件</el-button> </el-upload> </div>
复制
data中:
//上传后的文件列表 fileList: [], // 允许的文件类型 fileType: [ "pdf", "doc", "docx", "xls", "xlsx","txt","png","jpg", "bmp", "jpeg"], // 运行上传文件大小,单位 M fileSize: 50, // 附件数量限制 fileLimit: 5, //请求头 headers: { "Content-Type": "multipart/form-data" },
复制
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(){ },
复制
齐活,如果你觉得还ok,那就点个赞吧,哈哈哈