首页 > 其他分享 >SpringBoot项目前端使用vue下载后端resources下的文件(导出模板)

SpringBoot项目前端使用vue下载后端resources下的文件(导出模板)

时间:2023-01-31 18:14:28浏览次数:46  
标签:vue SpringBoot close byte null xls response resources out

 

放到resources/xls/import-template.xls 这个路径可以自己修改 代码同步修改即可

 

@GetMapping(value = "/downloadXls")
    @ApiOperation(value = "下载导入模板")
    public void downloadXls(HttpServletResponse response) throws Exception {
        InputStream in = null;
        OutputStream out = null;
        try {
            InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("xls/import-template.xls");
            //强制下载不打开
            response.setContentType("application/force-download");
            out = response.getOutputStream();
            //使用URLEncoder来防止文件名乱码或者读取错误
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode("导入模板.xls", "UTF-8"));
            int b = 0;
            byte[] buffer = new byte[1000000];
            while (b != -1) {
                b = inputStream.read(buffer);
                if (b != -1) {
                    out.write(buffer, 0, b);
                }
            }
            int bytes = 0;
            byte[] bufferOut = new byte[1024];
            while ((bytes = in.read(bufferOut)) != -1) {
                out.write(bufferOut, 0, bytes);
            }
            out.close();
            in.close();
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    log.error("文件流关闭失败", e);
                }
            }

            if (null != out) {
                out.close();
            }

        }

    }

 

标签:vue,SpringBoot,close,byte,null,xls,response,resources,out
From: https://www.cnblogs.com/pxblog/p/17080104.html

相关文章