springBoot 下载通用代码模板

搬砖过程中常用的springBoot下载代码模板,复制用就行了。【2022-11-29 为方便小白,二次更新】

一、controll

//controll 层

    @GetMapping("/excelDown")
    public void dataModuleExcelDown(HttpServletRequest request,
                                    HttpServletResponse response) throws UnsupportedEncodingException {
        dataCategoryService.excelDown(request,response);
    }

二、server 

//server层

public void excelDown(HttpServletRequest request,HttpServletResponse response) throws UnsupportedEncodingException {
        //1.读取文件流
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        String prefix = ".xlsx";
        String fileName = "template";
        String filePath = "/template/" + fileName + prefix;


        ClassPathResource classPathResource = new ClassPathResource( filePath );
        InputStream in = classPathResource.getStream();

        request.setCharacterEncoding( "UTF-8" );
        String userAgent = request.getHeader( "User-Agent" );
        try {
            if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
                fileName = URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 非IE浏览器的处理:
                fileName = new String((fileName).getBytes("UTF-8"), "ISO-8859-1");
            }

            response.reset();
            response.setContentType( "application/octet-stream" );
            response.addHeader( "content-disposition", "attachment; filename=" + fileName + prefix);

            bis = new BufferedInputStream( in );
            bos = new BufferedOutputStream( response.getOutputStream() );

            byte[] bytes = new byte[2048];
            int len;

            while ( (len = bis.read( bytes, 0, bytes.length )) != -1 ) {
                bos.write( bytes, 0, len );
            }
        } catch (Exception e) {
            throw new RuntimeException( e );
        } finally {
            if (bis != null) {
                try {
                    bis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (bos != null) {
                try {
                    bos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

三、资源文件路径

四、坑,如果有下载下来打不开的,参考我这篇文章

springBoot 下载文件打不开,提示损坏解决方案_大叔0769的博客-优快云博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值