码迷,mamicode.com
首页 > 其他好文 > 详细

字符串转输出流下载代码

时间:2020-05-22 19:49:03      阅读:48      评论:0      收藏:0      [点我收藏+]

标签:back   nes   catch   ati   osi   class   exce   message   adr   

@GetMapping("/rollback/content/download")
    public void downloadRollbackContent(@RequestParam("sqlId") Integer sqlId,
                                        @RequestParam("taskId") Integer taskId,
                                                    HttpServletResponse response){
        // 注意这里一定要用StringBuilder包装一下String,不然下载不下来,不知为何
        StringBuilder sb = new StringBuilder("sssssssss");
        InputStream is = null;
        String fileName = System.currentTimeMillis() + "" + taskId + "" + sqlId + ".sql";

        //使用流的形式下载文件
        try {
            //加载文件
            is = new BufferedInputStream(new ByteArrayInputStream(sb.toString().getBytes("utf-8")));;
            response.addHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"), "ISO-8859-1"));
            response.addHeader("Content-Length", "" +sb.toString().length());
            response.setContentType("application/octet-stream");
            response.setContentLengthLong(sb.toString().length());
            BufferedOutputStream outStream = new BufferedOutputStream(response.getOutputStream());
            byte[] buffer = new byte[1024];
            int bytesRead = 0;
            while ((bytesRead = is.read(buffer)) != -1) {
                outStream.write(buffer, 0, bytesRead);
            }
            outStream.flush();
        } catch (Exception e) {
            log.error("获取附件失败", e);
            throw new BusinessException(e.getMessage());
        }finally {
            try {
                if (null != is) {
                    is.close();
                }
            } catch (IOException ioEx) {
                log.error("", ioEx);
            }

        }
    }

 

字符串转输出流下载代码

标签:back   nes   catch   ati   osi   class   exce   message   adr   

原文地址:https://www.cnblogs.com/guoAIrong/p/12938775.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!