字符串转输出流下载代码

Posted guoairong

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了字符串转输出流下载代码相关的知识,希望对你有一定的参考价值。

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

        }
    }

 

以上是关于字符串转输出流下载代码的主要内容,如果未能解决你的问题,请参考以下文章

(转) Java中的负数及基本类型的转型详解

java 字节流与字符流的区别(转)

16个必备的JavaScript代码片段

web代码片段

片段(Java) | 机试题+算法思路+考点+代码解析 2023

文件下载关键代码