提交表单时有个字段内容需要从导入的Excel中获取,所以提交方式需要改变一下,将upload和form整合到一起提交后台
核心代码如下
页面代码
<el-form-item v-show="form.receiveType == 1">
<el-upload
ref="upload"
:limit="1"
accept=".xlsx, .xls"
:headers="upload.headers"
:action="upload.url"
:disabled="upload.isUploading"
:on-progress="handleFileUploadProgress"
:on-success="handleFileSuccess"
:auto-upload="false"
:on-change="handleFileChange"
:on-remove="handleRemove"
:http-request="handleHttpRequest"
:class="{hide:upload.hideUpload}"
>
<el-button size="small" type="primary">点击上传</el-button>
<div class="el-upload__tip" slot="tip">
<el-link href="a.xlsx" download="导入模板" target="_blank">下载模板</el-link>
</div>
<div class="el-upload__tip" style="color:red" slot="tip">提示:仅允许导入“xls”或“xlsx”格式文件!</div>
</el-upload>
</el-form-item>
<el-button type="primary" @click="submitForm">确 定</el-button>
js代码
/** 提交按钮 */
submitForm() {
if (this.form.receiveType == 1) {//是否需要上传excel
if (!this.upload.hideUpload) {
this.$message.error('请先上传文件。')
return;
}
this.$refs.upload.submit();//submit后会触发upload组件的http-request方法 即 handleHttpRequest
} else {
this.handleHttpRequest()
}
},
//发起请求
handleHttpRequest(item) {
let formData = new FormData()
if (this.form.receiveType == 1) {//是否需要上传excel
if (!this.upload.hideUpload) {//这里的hideUpload是在上传文件达到limit后隐藏上传按钮
this.$message.error('请先上传文件。')
return;
}
formData.append('file', item.file)
}
formData.append("data", JSON.stringify(this.form))
createNoticeInfo(formData).then(response => {
this.upload.open = false;
this.upload.isUploading = false;
this.$refs.upload.clearFiles();
if (response.data.needImportUsers == 0) {
this.importResultData = response.data
this.loading = false;
this.importLoading = false
this.dialogImportAlertVisible = true
} else {
this.msgSuccess("新增成功");
}
this.open = false;
this.getList()
}).catch(err => {
console.log(err)
})
},
handleFileChange(file, fileList){
this.upload.hideUpload = fileList.length >= 1;
},
handleRemove(files, fileList){
this.upload.hideUpload = fileList.length >= 1;
},
样式代码 用于隐藏upload
<style>
.hide .el-upload {
display: none;
}
</style>
spring boot后台controller核心代码
public void create(@RequestParam(value ="file", required =false) MultipartFile file,
@RequestParam("data") String jsonStr)throws Exception {
JSONObject createReqVoJsonObject = JSONObject.parseObject(jsonStr);
List list = ExcelUtils.read(file, KkProjectStatusConfigUsersImportVO.class,1);
}