SpringBoot上传和下载文件(二十七)下

简介: SpringBoot上传和下载文件(二十七)下

三. 下载文件

传入文件的路径 (包括名称) 进行下载.

@GetMapping("download")
    public void download(String fileName, HttpServletResponse response) throws IOException {
        // 获得待下载文件所在文件夹的绝对路径
        String realPath =uploadFilePath;
        // 获得文件输入流
        FileInputStream inputStream = new FileInputStream(new File(realPath, fileName));
        // 设置响应头、以附件形式打开文件
        response.setHeader("content-disposition", "attachment; fileName=" + fileName);
        ServletOutputStream outputStream = response.getOutputStream();
        int len = 0;
        byte[] data = new byte[1024];
        while ((len = inputStream.read(data)) != -1) {
            outputStream.write(data, 0, len);
        }
        outputStream.close();
        inputStream.close();
    }

前端点击文件下载,便可以进行下载

image.png


四. 文件上传和下载- Excel

项目开发中,常常将数据从 Excel 中导入, 将数据导出成 Excel.


我们用 alibaba 的 easyExcel 进行处理.


四.一 pom.xml 添加依赖

<!--添加easyExcel 上传excel文件-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>easyexcel</artifactId>
            <version>2.2.9</version>
        </dependency>


四.二 实体 User 定义

@Data
public class User {
    @ExcelProperty(value="id编号")
    private Integer id;
    @ExcelProperty("姓名")
    private String name;
    @ExcelProperty("性别")
    private String sex;
    @ExcelProperty("年龄")
    private Integer age;
    @ExcelProperty("描述信息")
    private String description;
}


上传的文件内容是: 员工表.xlsx

image.png



四.三 上传Excel文件

/**
     * 上传Excel文件,获取文件里面的内容.
     * @date 2021/11/4 21:12
     * @author zk_yjl
     * @return
     */
    @PostMapping("/uploadExcel")
    @ResponseBody
    public String uploadExcel(@RequestParam MultipartFile file) throws IOException {
        String realPath =uploadFilePath;
        File newFile = new File(realPath);
        // 如果文件夹不存在、则新建
        if (!newFile.exists()){
            newFile.mkdirs();
        }
        // 上传
        File uploadFile=new File(newFile, file.getOriginalFilename());
        file.transferTo(uploadFile);
        InputStream inputStream=new FileInputStream(uploadFile);
        System.out.println(">>>>>>>>>>>>>>读取到List里面");
        //同步进行读取数据,会放置在内存里面.
        List<User> userList=EasyExcel.read(inputStream).head(User.class).
                sheet(0).doReadSync();
        for(User user:userList){
            System.out.println(">>>读取记录:"+user);
        }
        String uploadPath=realPath+"/"+file.getOriginalFilename();
        return "上传文件成功,地址为:"+uploadPath;
    }

image.png

将文件进行上传, 控制台打印输出


image.png


四.四 Excel 文件下载

/**
     * 下载Excel文件
     * @date 2021/11/4 21:12
     * @author zk_yjl
     * @return
     */
    @GetMapping("/downloadExcel")
    @ResponseBody
    public void downloadExcel(HttpServletResponse response,String name) throws IOException {
        //1. 通过传入的参数,和相关的业务代码逻辑处理,获取相应的数据.
        //2. 将数据进行转换,转换成 List<User> 的形式.
        List<User> dataList=createDataList(name);
        //将数据进行下载.
        // 这里注意 有同学反应使用swagger 会导致各种问题,请直接用浏览器或者用postman
        try {
            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("员工表", "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), User.class).autoCloseStream(Boolean.FALSE).sheet("员工")
                    .doWrite(dataList);
        } catch (Exception e) {
            // 重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            JSONObject jsonObject=new JSONObject();;
            response.getWriter().println(jsonObject.toString());
        }
    }
    private List<User> createDataList(String name) {
        List<User> result=new ArrayList<>();
        for(int i=1;i<=10;i++){
          User user=new User();
          user.setId(i);
          user.setName(name+"_"+i);
          user.setSex(i%2==0?"女":"男");
          user.setAge(20+i);
          user.setDescription("我是第"+i+"个,我的名字是:"+user.getName());
          result.add(user);
        }
        return result;
    }

image.png

点击后,进行下载

image.png


image.png



上传和下载文件均是成功的.


相关文章
|
11天前
|
Java 容器
SpringBoot读取resources下的文件以及resources的资源路径
SpringBoot读取resources下的文件以及resources的资源路径
38 0
|
11天前
|
Java 数据库连接 mybatis
springboot访问jsp页面变成直接下载?
springboot访问jsp页面变成直接下载?
95 0
|
11天前
|
Java
SpringBoot文件上传单文件多文件上传
SpringBoot文件上传单文件多文件上传
14 0
|
10天前
|
XML JavaScript 前端开发
springboot配合Freemark模板生成word,前台vue接收并下载【步骤详解并奉上源码】
springboot配合Freemark模板生成word,前台vue接收并下载【步骤详解并奉上源码】
|
11天前
|
Java 关系型数据库 MySQL
【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口(下)
【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口
52 0
|
11天前
|
Java 关系型数据库 MySQL
【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口(上)
【MySQL × SpringBoot 突发奇想】全面实现流程 · xlsx文件,Excel表格导入数据库的接口
56 0
|
11天前
|
前端开发 关系型数据库 MySQL
【MySQL × SpringBoot 突发奇想】全面实现流程 · 数据库导出Excel表格文件的接口
【MySQL × SpringBoot 突发奇想】全面实现流程 · 数据库导出Excel表格文件的接口
38 0
|
11天前
|
JavaScript Java API
【JavaEE】Spring Boot - 日志文件
【JavaEE】Spring Boot - 日志文件
6 0
|
11天前
|
安全 JavaScript Java
springboot实现文件防盗链设计
`shigen`,一位专注于Java、Python、Vue和Shell的博主,分享成长和技术。近期将探讨SpringBoot实现图片防盗链,通过限制`Referer`防止资源被盗用。基础版通过`WebMvcConfigurer`配置静态资源,升级版添加拦截器检查`Referer`,确保请求来源合法性。详细代码实现和案例可在文中链接找到。一起学习,每天进步!
52 13
springboot实现文件防盗链设计
|
11天前
|
Java 数据安全/隐私保护 开发者
【SpringBoot】讲清楚日志文件&&lombok
【SpringBoot】讲清楚日志文件&&lombok
30 5