有校验手机号和邮箱以及其他的枚举校验。可以参考
Controller :
/**
* 导入用户数据
* @param file
* @return
*/
@RequestMapping(value = "/import", method = RequestMethod.POST)
public UserCentreResponse importUser(@RequestPart("file") FilePart file) {
UserCentreResponse userCentreResponse = new UserCentreResponse();
List<String> errorList = new ArrayList<>();
String fileName = null;
if (file != null) {
fileName = file.filename();//getOriginalFilename();
try {
errorList = userService.batchImport(fileName, file);
} catch (Exception e) {
log.error(e.getMessage(), e);
}
userCentreResponse.setValue("导入成功!", errorList);
return userCentreResponse;
}else {
return userCentreResponse.setError(400, "请导入文件!");
}
}
Service:
/**
* 导入用户信息
* @param fileName
* @param file
* @return
*/
@Override
@Transactional(rollbackFor = Exception.class)
public List<String> batchImport(String fileName, FilePart file) throws Exception {
boolean notNull = false;
List<User> userList = new ArrayList<User>();//用来存储user
List<String> errorList = new ArrayList<>();//存储错误信息
if (!fileName.matches("^.+\\.(?i)(xls)$") && !fileName.matches("^.+\\.(?i)(xlsx)$")) {
errorList.add("上传文件格式不正确");
throw new RuntimeException ("上传文件格式不正确");
}
boolean isExcel2003 = true;
if (fileName.matches("^.+\\.(?i)(xlsx)$")) {
isExcel2003 = false;
}
//上传的文件的临时存放目录
String tempDir=File.pathSeparator+"tmp";
StringBuilder tempFilePath=new StringBuilder(tempDir).append(File.pathSeparator).append(UUID.randomUUID())
.append("_").append(fileName);
//将上传的文件保存到临时文件
File tempFile=new File(tempFilePath.toString())