首先,先写一个js文件,直接把下面这段复制进去
其次,解释一下代码内容:
$("#excel")[0]为固定写法,其中$("#excel")为获取id为excel的html标签,这个标签肯定是一个input框,类型为file,[0]获取第一个(一般html中id是唯一的);
url为后端访问的地址,只需修改这两处就可以实现上传文件到后端了
使用时,将uploadService注入你的控制器,调用uploadService.upload()方法即可
app.service('uploadService',function($http){
/*
anjularjs 对于 post 和 get 请求默认的 Content-Type header 是 application/json。
通过设置 ‘Content-Type’: undefined,这样浏览器会帮我们把 Content-Type 设置为
multipart/form-data.
通过设置 transformRequest: angular.identity ,anjularjs transformRequest function将序列化 我们的 formdata object.
*/
this.upload = function () {
var formData=new FormData();
formData.append("file",$("#excel")[0].files[0]);
return $http({
method:'POST',
url:"attachmentUpload",
data: formData,
headers: {'Content-Type':undefined},
transformRequest: angular.identity
});
}
})
后端代码就没什么好说的了
@ResponseBody
@PostMapping("/attachmentUpload")
public String parseExcel(MultipartFile file){
try {
InputStream fileInputStream = file.getInputStream();
ExcelReader excelReader = ExcelUtil.getReader(fileInputStream);
//自定义标题别名
Map<String, String> alias = Maps.newLinkedHashMap();
alias.put(ExcelConstants.NUM, "num");
alias.put(ExcelConstants.PROPOSERNAME, "proposerName");
alias.put(ExcelConstants.HOUSEHOLDREGION, "houseHoldName");
alias.put(ExcelConstants.LOCALITYREGION, "localityName");
alias.put(ExcelConstants.CARDNUM, "cardNum");
alias.put(ExcelConstants.NOTARY, "notary");
alias.put(ExcelConstants.USE_COUNTRY, "use_country");
alias.put(ExcelConstants.LANGUAGE, "language");
alias.put(ExcelConstants.AUTH_NUM, "auth_num");
alias.put(ExcelConstants.USE, "use");
alias.put(ExcelConstants.REMARK, "remark");
excelReader.setHeaderAlias(alias);
List<ExcelOrderDTO> list = excelReader.readAll(ExcelOrderDTO.class);
return "";
} catch (IOException e) {
// SYS_LOGGER.error("excel解析异常",e);
}
return null;
}