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();
        }

    }

方法可直接使用

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章