springboot下载txt接口

    @Override
    public void downloadKey(Long companyId) {

        CompanyInfo companyInfo = this.getById(companyId);

        if (companyInfo.getApiKey() == null || companyInfo.getPrivateKey() == null || companyInfo.getPublicKey() == null) {
            throw new ServiceException("下载失败:请先生成密钥!");
        }

        HttpServletResponse response = ServletUtil.getResponse();
        response.setCharacterEncoding("utf-8");
        //设置响应的内容类型
        response.setContentType("text/plain");
        //设置文件的名称和格式
        response.addHeader("Content-Disposition", "attachment;filename=key.txt");
     // 在try的括号中引用的资源可以自动关闭,不需要buff.close()
try ( ServletOutputStream outStr = response.getOutputStream(); BufferedOutputStream buff = new BufferedOutputStream(outStr) ) { String text = "ApiKey:" + companyInfo.getApiKey() + "\n"; text += "-----BEGIN PRIVATE KEY-----\n" + companyInfo.getPrivateKey() + "\n-----END PRIVATE KEY-----"; buff.write(text.getBytes("UTF-8")); buff.flush(); } catch (Exception e) { e.printStackTrace(); } }

 

posted @ 2023-05-26 09:48  fnasklf  阅读(334)  评论(0编辑  收藏  举报