5.前后端分离

发布于:2024-04-20 ⋅ 阅读:(23) ⋅ 点赞:(0)

目录

一、前后端分离上传文件

1.在yml中设置port和localhost

2.如何使用postman测试上传文件的接口

二、如何导出excel文件

​编辑1.在pom.xml中导包

2.在实体类中给每个字段添加注解,导出表格时,列名将会改为对应的中文

3.controller中方法的具体代码


一、前后端分离上传文件

1.在yml中设置port和localhost

yml文件:

contorller文件:

使用两个value注解用于接收变量的值

这样做的好处是,后期在云服务器部署时,只需要在yml中修改localhost即可。

2.如何使用postman测试上传文件的接口

1.可以使用Body,选择为变量类型为file

2.使用binary,点击上传

二、如何导出excel文件


1.在pom.xml中导包

        <!--导出文件需要的依赖 -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>5.2.3</version>
        </dependency>

​

2.在实体类中给每个字段添加注解,导出表格时,列名将会改为对应的中文

添加@Alias注解的前后效果:

3.controller中方法的具体代码

 /**
     * 批量导出数据
     * 文件下载类型的数据通常使用void
     * required = false 可以不传
     */
    @GetMapping("/export")
    public void exportData(@RequestParam(required = false) String username,
                           @RequestParam(required = false) String name,
                           HttpServletResponse response) throws IOException {
        //写入excel表中
        ExcelWriter writer = ExcelUtil.getWriter(true);
        List<User> list = new ArrayList<>();
        //1.全部导出
        if(StrUtil.isBlank(username) &&StrUtil.isBlank(name)){
            list = userService.list(); //查询出当前user表的所有数据
        }
        writer.write(list,true);



        //导出excel,必须设置的浏览器格式
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        //设置导出文件的名称 inline预览,attachment附件
        response.setHeader("Content-Disposition","attachment;filename="+ URLEncoder.encode("用户信息表","UTF-8") + ".xlsx");


        //通过response写成流的方式
        ServletOutputStream outputStream = response.getOutputStream();
        writer.flush(outputStream,true);//把writer中的对象刷新到数据流outputStream中
        writer.close();
        //isCloseOut是否在刷新完成后关闭输出流
        outputStream.flush();//刷新
        outputStream.close();//关闭
    }