A服务的文件下载接口是直接返回流文件,B服务现在需要去调用A服务,接收A服务返回的流文件的处理方式如下。

服务提供者:

服务调用方

    /**
     * 文件压缩下载
     * @param request
     */
    @PostMapping("/file/download/zip")
    Response downloadFileZip(@RequestBody BatchRenameDownloadRequest request);

 需要注意的是,这里返回值需要用  feign.Response 来接收,最后我们来看下如何对接收  的 feign.Response 进行转化

/**
     * 下载文件
     * @param response
     * @param feignResponse
     * @throws Exception
     */
    public void downLoadFile(HttpServletResponse response, Response feignResponse) throws Exception {

        InputStream inputStream = null;
        BufferedInputStream bufferedInputStream = null;
        OutputStream outputStream = null;
        try {
            // 设置ContentType,响应内容为二进制数据流,编码为utf-8,此处设定的编码是文件内容的编码
            response.setContentType("application/octet-stream;charset=utf-8");
            //这一段代码是为了保持服务提供者一致的文件下载输出,其中就包括文件名!
            response.setHeader("Content-Disposition", feignResponse.headers().get("Content-Disposition").toString().replace("[","").replace("]",""));
            inputStream = feignResponse.body().asInputStream();
            //使用这个buffereInputStream 为了防止大文件内存溢出
            bufferedInputStream = new BufferedInputStream(inputStream);
            outputStream = response.getOutputStream();
            //每次取出5M
            byte[] buffer = new byte[1024 * 1024 * 5];
            int len;
            while ((len = bufferedInputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, len);
            }
        } catch (Exception e) {
            log.error("下载文件异常:{}", e);
        } finally {
            if (inputStream!=null){
                inputStream.close();
            }
            if (outputStream!=null){
                outputStream.close();
            }
            if (bufferedInputStream!=null){
                bufferedInputStream.close();
            }
        }
    }

经过测试,B服务调用A服务的文件下载接口,正常下载文件

Logo

魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。

更多推荐