使用a-upload-dragger上传xml文件
使用a-upload-dragger上传xml文件
·
最近在做工作流相关的工作,在使用a-upload-dragger组件上传xml文件时遇到一些问题,在此记录一下:
一、这是文件上传的界面
二、以下是相关的代码
html部分:
这里上传文件使用的是ant-design-vue的a-upload-dragger组件,实现了既可以点击上传又可以拖拽上传文件
<a-upload-dragger
name="file"
:multiple="false"
:file-list="model.fileList"
:remove="handleRemove"
:before-upload="beforeUpload"
style="width: 100%"
@change="handleChange">
<p class="ant-upload-drag-icon"><a-icon type="inbox" /></p>
<p class="ant-upload-text">将文件拖到此处,或 <a>点击上传</a></p>
</a-upload-dragger>
js部分:
因为文件需要在点击确定后上传,所以不能自动上传,beforeUpload方法的返回值必须是false。这个方法可以在文件上传前检查文件的类型,以提示用户是否上传错误。
beforeUpload(file) {
//检查文件后缀名是否为.bpm或.xml
const isBpmOrXml = file.type === 'text/xml' || /\.(bpm|xml)$/i.test(file.name);
if (!isBpmOrXml) {
this.$message.error('你只能导入“bpm”或“xml”格式文件!');
}
return false;
},
在移除文件时调用这个方法,因为只允许上传一个文件,所以直接将fileList置空。
handleRemove(){
this.model.fileList = [];
},
在文件上传或移除时都会触发这个方法,文件上传时status为undefined,移除时为removed ,因此只有上传时才会执行this.model.fileList[0] = info.file。注意:这里容易出错的是如果写成this.model.fileList[0] = info.fileList[0]是不对的,因为info.fileList[0].originFileObj才是真正的file文件,所以使用this.model.fileList[0] = info.fileList[0].originFileObj也是正确的
handleChange(info) {
const status = info.file.status;
if (!status) {
// this.model.fileList[0] = info.fileList[0].originFileObj
this.model.fileList[0] = info.file
}
},
点击确定后调用handleOk方法发送post请求,但我们需要将model里的参数转为FormData类型,这样才能正确传送文件和其他信息
handleOk () {
const that = this;
// 触发表单验证
this.$refs.form.validate(valid => {
if (valid) {
that.loading = true;
const formData = new FormData();
formData.append("bpmnFile", this.model.fileList[0]);
formData.append("key", this.model.key);
formData.append("name", this.model.name);
formData.append('description',this.model.description)
httpAction(this.url.import,formData,"post").then((res)=>{
if(res.success){
that.$message.success(res.message);
that.model={fileList:[],};
that.visible = false;
that.$emit('success');
}else{
that.$message.warning(res.message);
}
}).finally(() => {
that.loading = false;
})
}
})
},
而后端接口使用对应的实体类来接收即可,不需要加@RequestBody
以上仅供参考!
更多推荐
所有评论(0)