2021-10-22vue+elment上传组件实现导入功能
作者:互联网
vue+elment上传组件实现导入功能
记录
如果并不是直接上传文件,两个步骤:
1.el-upload组件中设置::auto-upload=“false”
2.在对应的上传点击事件中:this.$refs.upload.submit();
代码
<el-dialog
append-to-bod
:close-on-click-modal="false"//是否点击弹窗外关闭
:before-close="cancel" //关闭签调用
:visible.sync="isUpload"//是否可见
title="导入评测项目" //标题
width="500px"
>
<el-form
ref="uploadForm"
size="small"
label-width="100px"
:model="uploadForm"
:rules="uploadRules"//导入规则
>
<!-- 上传文件 -->
<el-form-item label="上传" prop="fileList">
<el-upload
ref="upload"
:on-change="onChange"//通过 on-change 钩子函数来对列表进行控制
:file-list="uploadForm.fileList"//是否在选取文件后立即进行上传
:limit="2"//文件数目限制
:auto-upload="false"//是否自动上传文件
:action="uploadUrl"//必选参数,上传的地址
:http-request="uploadAction"//覆盖默认的 xhr 行为,允许实现自己的上传文件请求
>
<div class="eladmin-upload">
<i class="el-icon-upload" /> 添加文件
</div>
<div slot="tip" class="el-upload__tip">
只可上传xlsx格式文件,且不超过100M
</div>
</el-upload>
</el-form-item>
</el-form>
<div slot="footer" class="dialog-footer">
<el-button type="text" @click="cancel">取消</el-button>
<el-button :loading="uploading" type="primary" @click="upload"
>确认</el-button
>
</div>
</el-dialog>
data中
uploadUrl: "",
uploadForm: {
fileList: [],
},
file: "",
uploadRules: {
fileList: [
{ required: true, message: "上传文件不能为空。", trigger: "blur" },
],
},
方法
onChange(file, fileList) {
if (fileList) {
this.uploadForm.fileList = fileList.slice(-1);
}//选取最新一个文件,文件切片
this.file = file;
},
cancel() {
this.isUpload = false;
this.clearFile();
this.uploadForm.fileList = [];
},
clearFile() {
const mainImg = this.$refs.upload;//upload对象
if (mainImg && mainImg.length) {
mainImg.forEach((item) => {
item.clearFiles();//清空已上传的文件列表
});
}
},
uploadAction() {
var data = new FormData();
data.append("file", this.file.raw);//添加一个新值到 FormData 对象内的一个已存在的键中,如果键不存在则会添加该键formData.append(name, value);
this.loading = true;
upload2(
this.baseApi + "",// getters中定义的baseApi: state => state.api.baseApi, http协议
data
).then((res) => {
this.loading = false;
if (res.data.success) {
this.$message("导入成功");
this.cancel();
} else {
this.$message.error(res.data.message);
this.cancel();
}
});
},
// 上传文件
upload() {
if (this.$refs["uploadForm"]) {
this.$refs["uploadForm"].validate((valid) => {
if (valid) {
if (!this.file || this.file.size === 0) {
this.$notify({
title: "请选择上传的文件",
type: "error",
duration: 2500,
});
return;
}
this.$refs.upload.submit();//验证通过后触发:http-request事件
}
});
}
},
//upload2方法
upload2(api, data) {
const config = {
headers: { 'Authorization': 'Bearer '+Vue.prototype.$keycloak.token, 'Content-Type': 'multipart/form-data' }//token和文件类型,header里面放Authorization,就是为了验证用户身份,Authorization里面放的就是token,就相当于每次发送请求的时候,拦截器都会拦截一次你的请求,
把你请求头部的Authorization拿出来,与当前存在服务器上的token做对比
}
return axios.post(api, data, config)
}
fileList中file包含
标签:10,上传,elment,fileList,upload,22vue,uploadForm,file,data 来源: https://blog.csdn.net/m0_46404694/article/details/120907609