java 上传txt json等类型文件解析后返回给前端
- 接口作用:
- 代码实现
接口作用:
1.后端解析前端上传文件的信息,并返回前端。
2.这样可以把文件内容存数据库,而不需要存文件。
代码实现
@PostMapping("/scriptUpload")
@ApiOperation(value = "上传附件", notes = "")
public Result scriptUpload(MultipartFile file, HttpServletRequest request) {
SysUserEntityVo uc = (SysUserEntityVo) request.getAttribute("UC");
return gClientScriptService.scriptUpload( file,uc);
}
注意:解析时一行一样解析,不然文件中的换行字符就没了,得到的是一个大字符串。
@Override
public Result scriptUpload(MultipartFile file, SysUserEntityVo uc) {
String fileName = file.getOriginalFilename();
StringBuffer sb = new StringBuffer();
String fileContent = "";
InputStream inputStream = null;
BufferedReader br = null;
try {
inputStream = file.getInputStream();
br = new BufferedReader(new InputStreamReader(inputStream));
String line = null;
while ((line = br.readLine()) != null) {
sb.append(line);
sb.append(System.lineSeparator());
}
fileContent = new String(sb);
// System.out.println(fileContent);
} catch (IOException e) {
e.printStackTrace();
}finally {
try {
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
JSONObject jsonObject = new JSONObject();
jsonObject.put("fileName",fileName);
jsonObject.put("fileContent",fileContent);
return Result.ok(jsonObject);
}