java下载文件流,不生成中间文件。

java下载文件流,不生成中间文件。

    • 代码设计:
    • 代码实现

代码设计:

从前端获取的数据经过后端加工后,生成文件流,并返回前端,(不生成中间文件,注意内存,记得关闭流)

代码实现

java 复制代码
    @ApiOperation(value = "下载文件", notes = "")
    @PostMapping("/getDownLoadScriptFile")
    public void getDownLoadScriptFile(@RequestBody ParamsObject vo, HttpServletRequest request, HttpServletResponse response) throws Exception {
        SysUserEntityVo uc = (SysUserEntityVo) request.getAttribute("UC");
        gClientScriptService.getDownLoadScriptFile(vo, uc,response);
    }
java 复制代码
  @Override
    public void getDownLoadScriptFile(ParamsObject vo, SysUserEntityVo uc, HttpServletResponse response) throws Exception {
        String fileContent = vo.getFileContent();
        String fileName = vo.getFileName();
        String encodeFileName = URLEncoder.encode(fileName);
        ServletOutputStream out = response.getOutputStream();

        try {
            //设置允许跨域的key
            response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
            //文件名有","等特殊字符发送到前端会报错,用""括起来解决
            response.addHeader("Content-Disposition", "attachment;filename=\"" + encodeFileName + "\"");
            //设置文件大小
            response.addHeader("Content-Length", "" + fileContent.getBytes().length);
            //设置文件名,避免问题,这个也用""括起来
            response.setHeader("filename,", "filename=\"" + encodeFileName + "\"");
            //设置文件类型
            response.setContentType("application/octet-stream");

            out.write(fileContent.getBytes(StandardCharsets.UTF_8));
            out.flush();

        } catch (Exception e) {
            throw e;
        } finally {
            try {
                out.close();
            } catch (Exception e) {
                throw e;
            }

            try {
                out.close();
            } catch (Exception e) {
                throw e;
            }
        }
    }
相关推荐
x***38163 小时前
springboot和springframework版本依赖关系
java·spring boot·后端
故事不长丨3 小时前
C#定时器与延时操作的使用
开发语言·c#·.net·线程·定时器·winform
hefaxiang3 小时前
C语言常见概念(下)
c语言·开发语言
S***84883 小时前
SpringSecurity踢出指定用户
java
p***s913 小时前
Spring数据库原理 之 DataSource
java·数据库·spring
adobehu3 小时前
麒麟系统安装jdk17
java·jdk
欧阳天风3 小时前
js实现鼠标横向滚动
开发语言·前端·javascript
spencer_tseng3 小时前
java.util.IllegalFormatPrecisionException
java·printf
虹科网络安全3 小时前
艾体宝干货 | Redis Java 开发系列#1 从零开始的环境搭建与实践指南
java·数据库·redis
铅笔侠_小龙虾4 小时前
Arthas 命令
java·jvm