因为在公司项目中有很多导入,图片导入,文件导入,写两个常用的留在这里
vue element upload
<el-upload
@click="test($event)"
class="upload-demo uploadArr"
list-type="picture-card"
:action="importFileUrl"
:headers="uploadHeader"
:on-success="(res,file)=>{return handleAvatarSuccess(res,file, item.fieldName)}"
:before-remove="beforeRemove"
:before-upload="beforeAvatarUpload"
:on-remove="(res,file)=>{return handleRemove(res,file, item.fieldName)}"
multiple
:limit="1" //限制文件上传个数
:on-exceed="handleExceed"
:file-list="form[item.fieldName]">
<i class="el-icon-plus"></i>
</el-upload>
下边我尽量写的详细点
click事件我在这里就不赘述了
1.因为有时候我们需要在导入是调取后台接口,登陆信息是通过拦截器添加的,需要在这里另外添加进去,或者有时候我们需要额外加一下请求头,这里都要定义一下。
computed: { //注意这些数据要写在computed里面
'importFileUrl':function(){
return url //这是接口Url string类型
},
'uploadHeader':function(){ //上传的请求头,我这里的数据是登陆token
return {
"Authorization":localStorage.getItem('h_token')
}
}
}
2.在官网的例子上,这些钩子函数传值一般都是定义好的,如果要额外多传值就例如上边:on-success="(res,file)=>{return handleAvatarSuccess(res,file, item.fieldName)}"这样传值,其中name是我需要的值,因为我的file-list是动态绑定的,不固定,所以我要在成功的钩子里把这个值保存起来,以便我的二次回显。res是调取接口返回的值。我把这些数据给了this.form[name],因为我要进行数据拼接。(这里说多了就是我项目的业务了)
.
// 保存图片
handleAvatarSuccess(res, file, name){
this.form[name].push({
name:file.name,
url: res.body.file,
})
},
3.限制文件上传数,首先vue中:limit=“1”,然后去钩子函数on-exceed里面写一下提示信息就可以了
handleExceed(files, fileList) {
this.$message.warning(`当前限制选择 1 个文件,本次选择了 ${files.length} 个文件,共选择了 ${files.length + fileList.length} 个文件`);
},
element的就写这么多把,其余的都是官网的钩子函数,如果有疑问,可以去官网看。
下边写一下js导入把
首先这是我在页面写的,仅仅是一个按钮和一个input,input需要隐藏,这里的导入只能导入一次
<!-- 导入 -->
<el-button type="primary" size="mini" @click="importExe">
<i class="el-icon-download"></i> {{this.$t("localization.common.import")}} //这里做了国际化中英文显示
</el-button>
<input type="file" @change="getFile($event)" style="display:none" ref="menuFile" />
// 导入
importExe() {
this.$refs.menuFile.value = "" //这里一定要清空
this.$refs.menuFile.click();
},
getFile(event) {
this.upath = event.target.files[0];
var zipFormData = new FormData();
zipFormData.append('file', this.upath);
this.loading = true
// this.inportErrorInfo = []
_fetch({ //这里的——fetch是我们封装的ajax
url: cmdb_basicsView.typeImport+this.aliasname,
method: "post",
headers: {
'Content-Type': 'multipart/form-data', // clientId:clientSecret => base64
},
data:zipFormData
}).then(response => {
} else {
})
.catch(error => {
});
},
1.在点击按钮的时候要对input清空,如果不清空的情况下,不再允许二次上传
2.导入调取接口的时候需要设置请求头headers: {
'Content-Type': 'multipart/form-data', // clientId:clientSecret => base64
},
一般默认是json,如图
这里还有一种方法设置请求头contentType:false,这里就截图看一下我写的另一个请求
3.这里还要注意与后台交互时所传数据,我这里传入的数据放在zipFormData中,其中命名为file
这是工作中的总结,也算是存档,如有疑问,可以留言一起讨论