Spring 下载附件

2023-05-11 18:00:55 浏览数 (1)

代码语言:javascript复制
    @GetMapping("/download-template")
    public void downloadTemplate(HttpServletResponse httpServletResponse) throws IOException {
        InputStream inputStream = null;
        // 读取Resource下的文件 "模版.xlsx" 获取其输入流 方式1
        inputStream = new ClassPathResource("模版.xlsx").getInputStream();
        //inputStream = getClass().getResourceAsStream("/模版.xlsx"); // 读取Resource下的文件 "模版.xlsx" 获取其输入流 方式2

        // 获取输出流
        ServletOutputStream outputStream = httpServletResponse.getOutputStream();
        // 指定文件名,这里需要注意一下,转为ISO-8859-1,不然不支持中文作为文件名称
        String fileName = "模版"   DateUtil.now()   ".xlsx";
        fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
        // 指定相应信息
        httpServletResponse.setContentType("application/vnd.ms-excel");
        httpServletResponse.setHeader("Content-disposition", "attachment;filename="   fileName);
        // COPY流
        byte[] buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = inputStream.read(buffer)) != -1) {
            outputStream.write(buffer, 0, bytesRead);
        }
        // 刷新输出流
        outputStream.flush();
        // 关闭相应的流
        outputStream.close();
        inputStream.close();
    }

0 人点赞