springboot读取上传的文件
Springboot文件上传与读取
·
在网上看到有许多文章都是讨论,怎样用springboot将文件上传至服务器的指定位置,但是最近接到一个新的需求,不需要将上传的文件保存至服务器,而是将文件内容读取后,以text文本格式存储在数据中
因此,本文的侧重点是:
1.如何从页面上选择文件上传
2.服务器如何接收并读取上传的文件
1.构建一个资源访问接口,用来获取文件上传页面
@GetMapping("/u")
public String uploadPage() {
return "index";
}
2.新建上传页面index.html在resource/templates目录下
index.html
<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8" />
<title>文件上传页面</title>
</head>
<body>
<h1>文件上传页面</h1>
<form method="post" action="/scenario/upload" enctype="multipart/form-data">
选择要上传的文件:<input type="file" name="file"><br>
<hr>
<input type="submit" value="提交">
</form>
</body>
</html>
3.构建文件接收与解析接口
controller层
@RequestMapping(value = "/upload", method = RequestMethod.POST, produces="text/html;charset=utf-8")
@ResponseBody
public String upload(MultipartFile file) {
//判断是否为空
if (file == null || file.isEmpty()) {
return "empty file";
}
service.uploadFile(file);
//读取成功返回文件名称
return file.getResource().getFilename() + " 已处理处理ok";
}
service层:
public void uploadFile(MultipartFile file) {
BufferedReader reader = null;
try {
//用流读取文件
reader = new BufferedReader(new InputStreamReader(file.getInputStream()));
String line;
StringBuffer content = new StringBuffer();
// 读取想定文件
while ((line = reader.readLine()) != null) {
content.append(line);
}
log.info("文件读取完毕 总行数 = {}"+content.length());
} catch (IOException e) {
} finally {
if (reader != null) {
IOUtils.closeQuietly(reader);
}
}
}
测试结果:
访问服务 http://localhost:8085/u
上传文件,提交
日志结果
更多推荐
已为社区贡献4条内容
所有评论(0)