java不生成实体文件直接返回流用户下载


    public void exportData(HttpServletResponse response, Long tenantId) {

        String title = System.currentTimeMillis()+"_角色权限";
        //定义文件格式
        String fileName = title + ".db";
        int bufferSize = 65000;


        //获取导出数据
        String data=getExportData(tenantId);
        byte[] bytes = new byte[0];
        try {
            bytes = data.getBytes ("utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }


        ByteArrayInputStream inputstream = new ByteArrayInputStream (bytes);

        try {
            byte abyte0[] = new byte[bufferSize];
            response.setContentType ("application/octet-stream; charset=utf-8");
            response.setContentLength ((int) bytes.length);
            response.setHeader ("Content-Disposition", "attachment;filename=" + new String (fileName.getBytes ("utf-8"), "ISO8859-1"));
            ServletOutputStream out = null;
            out = response.getOutputStream ();
            response.setCharacterEncoding ("utf-8");
            int sum = 0; int k = 0;
            while ((k = inputstream.read (abyte0, 0, bufferSize)) > -1)
            {
                out.write (abyte0, 0, k);
                sum += k;
            }
            inputstream.close ();
            out.flush ();
            out.close ();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

方法可直接使用

你可能感兴趣的:(java)