前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Spring 下载附件

Spring 下载附件

作者头像
收心
发布2023-05-11 18:00:55
4800
发布2023-05-11 18:00:55
举报
文章被收录于专栏:Java实战博客Java实战博客
代码语言: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();
    }
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档