上传文件配置
增加如下依赖:
io.github.openfeign.form feign-form-spring <!--3.2.2 --> io.github.openfeign.form feign-form 3.2.2
增加相关配置:
@Configuration public class FeignSupportConfig { @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(); } }
如果上传文件的时候有相关 requestbody 的参数接收
按照下面配置:
@Configuration public class MultipartSupportConfig { @Autowired private ObjectFactory messageConverters; @Bean @Primary @Scope("prototype") public Encoder feignEncoder() { return new SpringFormEncoder(new SpringEncoder(messageConverters)); } }
编写 feignclient
@FeignClient(name = "rpt-file-service", fallback = FileUploadServiceFallback.class, configuration = FileUploadService.UserFeignConfig.class) public interface FileUploadService { @RequestMapping(value = "/fdfs/upload", method = RequestMethod.POST,consumes= MediaType.MULTIPART_FORM_DATA_VALUE) @ResponseBody @CrossOrigin public Map upload(@RequestPart(value = "file", required = false) MultipartFile file) throws Exception; }
增加FeginInterceptor 后,文件上传失败的处理
为了服务之间调用传递token,同事增加了如下方法:
@Configuration public class FeginInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { try { Map headers = getHeaders(); for(String headerName : headers.keySet()){ requestTemplate.header(headerName, headers.get(headerName)); } }catch (Exception e){ e.printStackTrace(); } } private Map getHeaders(){ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); Map map = new LinkedHashMap(); Enumeration enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } }
以上方法拦截所有的feign请求,重新设置了请求头,但也拦截了文件上传的请求头,导致服务端接收到的文件为空,调用失败,解决这个问题,需要放开对文件上传服务的拦截,修改如下代码:
@Configuration public class FeginInterceptor implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { // 文件上传不拦截请求 if("/fdfs/upload".equals(requestTemplate.url())){ return; } try { Map headers = getHeaders(); for(String headerName : headers.keySet()){ requestTemplate.header(headerName, headers.get(headerName)); } }catch (Exception e){ e.printStackTrace(); } } private Map getHeaders(){ HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); Map map = new LinkedHashMap(); Enumeration enumeration = request.getHeaderNames(); while (enumeration.hasMoreElements()) { String key = enumeration.nextElement(); String value = request.getHeader(key); map.put(key, value); } return map; } }