Feign调用文件下载服务接口实例

简介: Feign调用文件下载服务接口实例

开发使用Feign做微服开发调用客户端时,几乎都是普通接口调用,返回一些JSON数据,

今天刚好要进行Feign客户端(服务消费者)调用服务提供者的文件下载接口,记录一下!代码如下:

服务提供者:

 @PostMapping(value = "/downLoadFile")
    public void downloadFile(@RequestParam String path, HttpServletResponse response) {
        File file = new File(path);
        FileUtil.fileDownload(response, file, false);
    }

FileUtil工具类

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class FileUtil {
   private static final Logger logger = LoggerFactory.getLogger(FileUtil.class);

   /**
    * 将指定文件对象写入到特定的Servlet响应对象,进而实现下载
    * 一般用于下载已经存在的文件
    *
    * @param response         目标Servlet响应对象
    * @param file             要下载的文件对象
    * @param isDeleteOriginal 是否删除服务器文件原本,true下载后将删除服务器上的文件
    */
   public static void fileDownload(HttpServletResponse response, File file, Boolean isDeleteOriginal) {
       try {
           InputStream inputStream = new FileInputStream(file);
           BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
           response.setContentType("multipart.form-data")
           response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(file.getName(), "UTF-8"));
           BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());

           int length = 0;
           byte[] temp = new byte[1024 * 10];
           while ((length = bufferedInputStream.read(temp)) != -1) {
               bufferedOutputStream.write(temp, 0, length);
           }
           bufferedOutputStream.flush();
           bufferedOutputStream.close();
           bufferedInputStream.close();
           inputStream.close();
           if (isDeleteOriginal) {
               file.delete();
           }
       } catch (FileNotFoundException e) {
           e.printStackTrace();
           logger.error(e.getMessage());
       } catch (IOException e) {
           e.printStackTrace();
           logger.error(e.getMessage());
       }
   }
}

Feign客户端(服务消费者)的代码

import feign.Response;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
 
@FeignClient(name = "file-service")
public interface UserFeignClient extends FeignClientParent {
    @GetMapping(value = "/update/downLoadFile",consumes = MediaType.APPLICATION_PROBLEM_JSON_VALUE)
    Response downloadFile(@RequestParam String path);
}

Feign客户端(服务消费者)的Controller接口方法

@GetMapping(value = "/downLoadFile")
    public void downloadFile(@RequestParam String path, HttpServletResponse response) {
        InputStream inputStream = null;
        try {
            Response serviceResponse = this.userFeignClient.downloadFile(path);
            Response.Body body = serviceResponse.body();
            inputStream = body.asInputStream();
            BufferedInputStream bufferedInputStream = new BufferedInputStream(inputStream);
            response.setContentType("multipart.form-data")
            response.setHeader("Content-Disposition", serviceResponse.headers().get("Content-Disposition").toString().replace("[","").replace("]",""));
            BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(response.getOutputStream());
            int length = 0;
            byte[] temp = new byte[1024 * 10];
            while ((length = bufferedInputStream.read(temp)) != -1) {
                bufferedOutputStream.write(temp, 0, length);
            }
            bufferedOutputStream.flush();
            bufferedOutputStream.close();
            bufferedInputStream.close();
            inputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

这一段代码是为了保持服务提供者一致的文件下载输出,其中就包括文件名!

serviceResponse.headers().get("Content-Disposition").toString().replace("[","").replace("]","")

原理:就是将服务提供者的文件下载响应的响应体(文件内容)复制到服务消费者对外的文件下载响应体中

相关文章
|
5月前
|
Java API Spring
SpringBoot项目调用HTTP接口5种方式你了解多少?
SpringBoot项目调用HTTP接口5种方式你了解多少?
421 2
|
5月前
|
存储 JSON Java
SpringBoot集成AOP实现每个接口请求参数和返回参数并记录每个接口请求时间
SpringBoot集成AOP实现每个接口请求参数和返回参数并记录每个接口请求时间
221 2
|
3月前
|
存储 前端开发 Java
SpringBoot使用云端资源url下载文件的接口写法
在Spring Boot中实现从云端资源URL下载文件的功能可通过定义REST接口完成。示例代码展示了一个`FileDownloadController`,它包含使用`@GetMapping`注解的方法`downloadFile`,此方法接收URL参数,利用`RestTemplate`下载文件,并将文件字节数组封装为`ByteArrayResource`返回给客户端。此外,通过设置HTTP响应头,确保文件以附件形式下载。这种方法适用于从AWS S3或Google Cloud Storage等云服务下载文件。
325 7
|
2月前
|
Dubbo JavaScript Java
SpringBoot 调用外部接口的三种方式
SpringBoot不仅继承了Spring框架原有的特性,还简化了应用搭建与开发流程。在SpringBoot项目中,有时需要访问外部接口或URL。本文介绍三种不使用Dubbo的方式:一是利用原生`httpClient`发起请求;二是使用`RestTemplate`,支持GET和POST请求,包括`getForEntity`、`getForObject`及`postForEntity`等方法;三是采用`Feign`客户端简化HTTP请求,需引入相关依赖并在启动类上启用Feign客户端。这三种方式均能有效实现对外部服务的调用。
114 0
课外作业(2)接口+工厂方法 文件上传题 1. 接口作业题
课外作业(2)接口+工厂方法 文件上传题 1. 接口作业题
|
12月前
|
Java API Spring
【异常】Feign 调用api模块直接进入fallback的问题解决办法
【异常】Feign 调用api模块直接进入fallback的问题解决办法
254 0
|
5月前
|
数据中心
Feign调用
Feign调用
30 0
|
11月前
|
前端开发 Java 对象存储
使用Feign接口实现文件上传的解决方案
一般的情况下,后端有个微服务,暴露出一个文件上传的restful接口给前端,前端调用该接口获取上传后的链接以及oss key值完成上传。假设提供restful接口的这个服务叫做A,现在有个微服务B有个本地文件,需要将本地文件调用A文件文件上传接口上传到文件服务器,该如何做?
98 0
|
Dubbo 网络协议 Java
网关调用其他项目的方法(RPC实现)
网关调用其他项目的方法(RPC实现)
117 0
|
Java API Apache
springboot 调用外部接口的21种方式
springboot 调用外部接口的21种方式
686 0