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;
            }
        }
    }
相关推荐
趣知岛19 小时前
初识Java
java·开发语言
步菲21 小时前
springboot canche 无法避免Null key错误, Null key returned for cache operation
java·开发语言·spring boot
毕设源码-朱学姐21 小时前
【开题答辩全过程】以 基于SpringBoot的中医理疗就诊系统为例,包含答辩的问题和答案
java·spring boot·后端
2201_757830871 天前
全局异常处理器
java
知远同学1 天前
Anaconda的安装使用(为python管理虚拟环境)
开发语言·python
小徐Chao努力1 天前
【Langchain4j-Java AI开发】09-Agent智能体工作流
java·开发语言·人工智能
CoderCodingNo1 天前
【GESP】C++五级真题(贪心和剪枝思想) luogu-B3930 [GESP202312 五级] 烹饪问题
开发语言·c++·剪枝
Coder_Boy_1 天前
SpringAI与LangChain4j的智能应用-(理论篇3)
java·人工智能·spring boot·langchain
kylezhao20191 天前
第1章:第一节 开发环境搭建(工控场景最优配置)
开发语言·c#
啃火龙果的兔子1 天前
JavaScript 中的 Symbol 特性详解
开发语言·javascript·ecmascript