前端(主要用了element官方组件):
<el-upload
class="upload-demo"
ref="upload"
:on-success="handleAvatarSuccess"//回调方法
:action="uploadTxt()"//后台接口
:on-remove="handleRemove"
:before-remove="beforeRemove"
accept=".txt">
<el-button type="primary" style="margin-top: 20px">上传62数据用户(txt)</el-button>
</el-upload>
后端controller(业务主要是读取txt插入数据):
@RequestMapping(value = "/uploadUserTxt",method = RequestMethod.POST)
public Map<String, Object> uploadUserTxt(@RequestParam("file") MultipartFile file) throws Exception {
return userInfoService.getUser(file);
}
service(重点):
public Map<String, Object> getUser(MultipartFile multipartFile) throws Exception {
Map<String, Object> resultMap = new HashMap<>();
resultMap.put("result", Constants.FAILURE_RESULT);//返回数据而已
resultMap.put("msg", Constants.UNKNOWN_FAILURE_RESULT);
File file = null;
file = File.createTempFile("tmp", null);
multipartFile.transferTo(file); //MultipartFile转File
file.deleteOnExit();
BufferedReader reader = null;
String temp = null;
int line = 1;
UserInfo userInfo = new UserInfo();
try {
int result = 0;
reader = new BufferedReader(new InputStreamReader(new FileInputStream(file),"UTF-8"));//解决服务器上乱码
while ((temp = reader.readLine()) != null) {
System.out.println("line" + line + ":" + temp);
//解析数据就不写了
line++;
}
if (result > 0) {
resultMap.put("result", Constants.SUCCESS_RESULT);
resultMap.put("msg", Constants.UPDATE_SUCCESS);
}else {
resultMap.put("msg", Constants.UPDATE_FAILED);
}
} finally {
if (reader != null) {
try {
reader.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return resultMap;
}