ElementUI 上傳文件前后端代碼
前端代碼如下:
importExcelBtn : function(){
if(this.dialogImportExcel.fileList==null || this.dialogImportExcel.fileList.length==0){
this.$message.error('文件必須上傳');
return
}
//var querystring = require('querystring') //原來用querystring 這種形式傳值
//var param = {}
//this.importExcel(querystring.stringify(param))//后臺捕獲不到文件數據
const multiForm = new FormData()//構建 FormData對象
if (this.dialogImportExcel.fileList !== null && this.dialogImportExcel.fileList.length > 0) {
this.dialogImportExcel.fileList.forEach(file => {
multiForm.append('files', file);
});
}
multiForm.append('isClear', this.dialogImportExcel.isClear)
let loadingInstance = this.$loading({
lock: true,
background: "rgba(0, 0, 0, 0.7)",
text: "正在導入數據,請不要刷新或關閉頁面",
});
this.importExcel(multiForm)
.then(resp => {
this.$message({
type: 'success',
message: '導入數據成功!'
});
this.dialogImportExcelVisible = false;
this.getSysConfig();
loadingInstance.close();//關閉loading
}).catch(() => {
loadingInstance.close();//關閉loading
});
},
后端代碼如下:
@PostMapping(value = "/importExcel")
public Response<String> importExcel( HttpServletRequest request,@RequestParam(value = "isClear", required = false) String isClear,
@RequestParam(value = "files", required = false) List<MultipartFile> files) {
long start=System.currentTimeMillis();
try {
synchronized (this) {
if (files.size()>0) {
MultipartFile multipartFile = files.get(0);
InputStream inputStream = multipartFile.getInputStream();;
try {
List<EntityVo> list = EasyExcel.read(inputStream).head(EntityVo.class).sheet().doReadSync();
List<Entity> dataslist=new ArrayList<>();
if(list!=null&&list.size()>0){
業務處理對應的數據
}else {
return Response.error("請導數有數據的excel。");
}
} finally {
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
System.out.println("運行時間:"+(System.currentTimeMillis()-start));
return Response.ok("保存成功");
} catch (Exception e) {
e.printStackTrace();
return Response.error("上傳失敗");
}
}
實體類
@Data
public class EntityVo{
@ExcelProperty(value = "姓名", index = 0)
private String A1;
@ExcelProperty(value = "性別", index = 1)
private String A2;
@ExcelProperty(value = "年齡", index = 2)
private String A3;
@ExcelProperty(value = "愛好", index = 3)
private String A4;
@ExcelProperty(value = "顏色", index = 4)
private String A5;
@ExcelProperty(value = "介紹", index = 5)
private String A6;
}

浙公網安備 33010602011771號