当前位置: 移动技术网 > IT编程>开发语言>Java > Feign实现跨服务文件上传下载

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

2019年07月19日  | 移动技术网IT编程  | 我要评论

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

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

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

<dependency> 
 <groupid>io.github.openfeign.form</groupid> 
 <artifactid>feign-form-spring</artifactid> 
 <version>3.2.2</version> 
</dependency> 
<dependency> 
 <groupid>io.github.openfeign.form</groupid> 
 <artifactid>feign-form</artifactid> 
 <version>3.2.2</version> 
</dependency>

②.上传的接口

@feignclient(value = "fdn-storage", configuration = {filefeignconfig.class})
public interface fileclient {

 string prefix_path = "/oss/files";
 /**
  * 上传存储文件
  * @param file
  * @return
  * @throws ioexception
  */
 @postmapping(value = prefix_path + "/", consumes = multipart_form_data_value)
 feignresult<fileentity> save(@requestpart(value = "file") multipartfile file) throws ioexception;
 }

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

@configuration
public class filefeignconfig {
 @autowired
 private objectfactory<httpmessageconverters> 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来作为返回值的

/**
  * 下载文件
  * @param id
  * @return
  * @throws ioexception
  */
 @getmapping(value = prefix_path + "/{id}/data")
 response download(@pathvariable("id") string id) throws ioexception;

②.外部服务的controller层调用

 /**
  *由id下载存储的文件
  */
 @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<string> 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);
  }
 }

至此,下载文件完成。

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

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网