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

2023-03-01 18:18:08 浏览数 (1)

文章目录[隐藏]

  • 上传
  • 下载

上传

文件上传服务

代码语言:javascript复制
@ApiOperation(value = "单文件上传")
@RequestMapping(value = "/upload", method = RequestMethod.POST,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public DataJsonResult uploadFile(@RequestPart("file") MultipartFile file){}

调用文件上传服务

jar包
代码语言:javascript复制
implementation group: 'io.github.openfeign.form', name: 'feign-form', version: '3.8.0' 
implementation group: 'io.github.openfeign.form', name: 'feign-form-spring', version: '3.8.0' 
配置类
代码语言:javascript复制
import feign.Logger;
import feign.codec.Encoder;
import feign.form.spring.SpringFormEncoder;
import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.cloud.openfeign.support.SpringEncoder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FileConfig {
    /**
     * 打开feign的日志
     * @return
     */
    @Bean
    Logger.Level feignLoggerLevel() {
        return Logger.Level.FULL;
    }
    /**
     * 涉及文件传输配置
     */
    class MultipartSupportConfig {
        @Autowired
        private ObjectFactory<HttpMessageConverters> messageConverters;
        @Bean
        public Encoder feignFormEncoder() {
            return new SpringFormEncoder(new SpringEncoder(messageConverters));
        }
    }
}
调用
代码语言:javascript复制
@RequestMapping(value = "/upload", method = RequestMethod.POST
,consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public DataJsonResult gridFsFile(@RequestPart("file") MultipartFile file);
注意:
代码语言:javascript复制
1.接口注解RequestMapping需要加入consumes=MediaType.MULTIPART_FORM_DATA_VALUE
2.参数注解@RequestPart(“file”)不能写成@RequestParam("file")。

下载

消费端

代码语言:javascript复制
import feign.Response;

@RequestMapping(value = "/download", method = RequestMethod.GET) public Response gridFsDownload(@RequestParam("fileId")String  fileId);

0 人点赞