需求:我司要求实现多文件上传,且要求使用formData传递参数。
环境:vue+element-ui+axios
实现:
1. 使用element-ui upload组件搭建上传文件页面,页面示例如下:
代码如下:
<template>
<div>
<el-upload :multiple="true" class="upload-demo" action="" drag="" ref="upload" :on-change="handleImport" :auto-upload="false" :http-request="uploadFile" name="file">
<i class="el-icon-upload"></i>
<div class="el-upload__text">
将文件拖到此处,或
<em>点击上传</em>
</div>
<div class="el-upload__text">
只能上传.xml文件
</div>
</el-upload>
<el-row :span="20">
<el-col :guter="20" align="left" style="margin-top:20px;">
<el-button size="small" type="primary" style="margin-right:10px;" @click="submitUpload">
确定
</el-button>
<el-button size="small" @click="handleCancel">
取消
</el-button>
</el-col>
</el-row>
</div>
</template>
2. data中设置两个变量fileList3和fileData,其中fileList3用来存储文件列表、fileData用来将文件追加到formData中
data() {
return {
fileList3: [],
fileData:''
};
},
3. 引入axios
import axios from 'axios'
4. 定义方法
// 导入文件时将文件存入数组中
handleImport(file, fileList) {
this.fileList3 = fileList
},
// 点击上传时覆盖默认上传事件
uploadFile:function(file){
this.fileData.append('file', file.file);
},
// 点击上传按钮
submitUpload(params) {
if(this.fileList3.length==0){
this.$message.error('请选择文件')
return
}
this.fileData = new FormData();
this.$refs.upload.submit();
var that = this;
axios({
method:"POST",
url: `你的接口地址`,
data:that.fileData,
contentType: false,//这里不要落下
dataType: 'json',
headers: { "Content-Type": "multipart/form-data",token:getStore("token") ? JSON.parse(getStore("token")) : ""},//其他需要追加到请求头的信息也可放入这里,我司需要追加一个token以做身份校验,同时利用表单上传Content-Type必须设置为multipart/form-data
}).then((res)=>{
let code =res.data.code
if(code==200){
this.$message({
message: '上传成功',
type: 'success'
});
}else{
this.$message.error(res.msg);
}
})
.catch((response)=>{
this.$message.error(response.msg);
})
}
5. 实现后的截图如下:
6. 后端是java,springMVC,附上后端代码
@OperationLog(operatorDesc = "上传数据源文件",moduleName = "数据源管理",isJsonFormat = false)
@RequestMapping("uploadFile")
public Object fileUpload(MultipartHttpServletRequest request){
try {
//获取文件集合
Map<String, MultipartFile> fileMap = request.getFileMap();
//判断文件是否为空
if(fileMap == null || fileMap.size() == 0){
return WebUtil.returnError("请上传文件");
}
Collection<MultipartFile> files = fileMap.values();
initFileService.upLoadFile(files);
} catch (Exception e) {
String message = LogUtil.formatErrorMessage("上传文件失败", e);
super.log.error(message);
return WebUtil.returnError("上传文件失败");
}
return WebUtil.returnOk("success");
}
如果有问题可以联系我哦:微信:lm13821687665,qq密码已经找不到所以只能放上微信了。