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

发布于:2025-02-11 ⋅ 阅读:(41) ⋅ 点赞:(0)

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


网站公告

今日签到

点亮在社区的每一天
去签到