栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

springboot读取上传的文件

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

springboot读取上传的文件

在网上看到有许多文章都是讨论,怎样用springboot将文件上传至服务器的指定位置,但是最近接到一个新的需求,不需要将上传的文件保存至服务器,而是将文件内容读取后,以text文本格式存储在数据中
因此,本文的侧重点是:
1.如何从页面上选择文件上传
2.服务器如何接收并读取上传的文件

1.构建一个资源访问接口,用来获取文件上传页面

 @GetMapping("/u")
    public String uploadPage() {
        return "index";
    }

2.新建上传页面index.html在resource/templates目录下

index.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

上传文件,提交

日志结果

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/995873.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号