栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

Feign实现跨服务文件上传下载

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Feign实现跨服务文件上传下载

本文实例为大家分享了Feign实现跨服务的文件上传下载操作,供大家参考,具体内容如下

1、跨服务文件上传,目前feign不支持调用文件上传接口,需要自行配置来满足feign的调用方式

①.首先需要在pom文件里添加feign依赖

 
 io.github.openfeign.form 
 feign-form-spring 
 3.2.2 
 
 
 io.github.openfeign.form 
 feign-form 
 3.2.2 

②.上传的接口

@FeignClient(value = "fdn-storage", configuration = {FileFeignConfig.class})
public interface FileClient {

 String PREFIX_PATH = "/oss/files";
 
 @PostMapping(value = PREFIX_PATH + "/", consumes = MULTIPART_FORM_DATA_VALUE)
 FeignResult save(@RequestPart(value = "file") MultipartFile file) throws IOException;
 }

③.添加配置来满足feign的调用

@Configuration
public class FileFeignConfig {
 @Autowired
 private ObjectFactory messageConverters;

 @Bean
 @Primary
 @Scope("prototype")
 public Encoder feignEncoder() {
  return new SpringFormEncoder(new SpringEncoder(messageConverters));
 }

 @Bean
 public feign.Logger.Level multipartLoggerLevel() {
  return feign.Logger.Level.FULL;
 }
}

④.外部服务的controller层调用

public class TestController extends baseRestController {
 @Autowired
 FileClient client;
 
 @PostMapping(value = "/" , consumes = MULTIPART_FORM_DATA_VALUE)
 public FileEntity save(@RequestPart(value = "file") MultipartFile file) throws IOException {
  FileEntity fileEntity = client.save(file).getData();
  return fileEntity;
 }
} 

到此位置就可以上传成功了

2、跨服务的文件下载

①.下载的接口(也是写在public interface FileClient),是用feign.Response来作为返回值的


 @GetMapping(value = PREFIX_PATH + "/{id}/data")
 Response download(@PathVariable("id") String id) throws IOException;

②.外部服务的controller层调用

 
 @GetMapping(value = "/{id}/data")
 public void downloadFile(@PathVariable String id, HttpServletResponse servletResponse) throws IOException {
  Response response = client.download(id);
  Response.Body body = response.body();
  for(Object key : response.headers().keySet()){
   List kList = (List)response.headers().get(key);
   for(String val : kList){
    servletResponse.setHeader(StringUtils.toString(key), val);
   }
  }
  try(InputStream inputStream = body.asInputStream();
   OutputStream outputStream = servletResponse.getOutputStream()
  ){
   byte[] b = new byte[inputStream.available()];
   inputStream.read(b);
   outputStream.write(b);
   outputStream.flush();
  }catch (IOException e){
   throw new RestException("IO流异常", e);
  }
 }

至此,下载文件完成。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持考高分网。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/138302.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号