在使用Element-ui的上传组件时,我们的业务场景经常是需要我们自定义上传接口、参数等。 那该如何实现呢?
ElementUI上传官方demo:
<el-uploadclass="upload-demo"action="https://jsonplaceholder.typicode.com/posts/":on-preview="handlePreview":on-remove="handleRemove":before-remove="beforeRemove"multiple:limit="3":on-exceed="handleExceed":file-list="fileList"><el-button size="small" type="primary">点击上传</el-button><div slot="tip" class="el-upload__tip">只能上传jpg/png文件,且不超过500kb</div></el-upload>
通过官方的api http-request 来覆盖掉默认的上传行为,可以自定义上传。
<el-uploadclass="upload-demo"action="#" //将默认接口改为 #accept=".jpg, .jpeg, .png" //限制上传文件:auto-upload="true" //关闭自动上传:http-request="upload" //自定义上传方法:show-file-list="false":before-upload="beforeIconUpload" //上传前校验><el-button size="small" type="primary">点击上传</el-button><div slot="tip" class="el-upload__tip">支持扩展名:.png .jpg</div></el-upload>
upload(file){//...上传操作}
这样就可以实现自定义上传来。
但是问题来了,有这么一个业务场景:一个页面多个上传操作,上传使用同一个接口,接口返回url,将url提交给后台。
那么我们难道要每一个上传都重复写一个上传方法吗,可不可以给每个上传带上特定的标识呢?答案是可以的。
<el-uploadclass="upload-demo"action="#"accept=".jpg, .jpeg, .png":auto-upload="true":http-request="(file)=>{uploadIcon(file,0,`${index}`)}":show-file-list="false":before-upload="beforeIconUpload"><el-button size="small" type="primary">点击上传</el-button><div slot="tip" class="el-upload__tip">支持扩展名:.png .jpg</div></el-upload>
通过改造http-request赋值的方法,取到file对象,同时自定义自己的参数。
upload(file,flag,index){//...上传操作}
这样就可以将上传操作写成公共方法,只要传入file对象与特定标识即可。
