spring boot: 2.3.4.RELEASE
java: 1.8
参数配置io.github.openfeign.form feign-form3.0.3 io.github.openfeign.form feign-form-spring3.0.3 commons-fileupload commons-fileupload1.3.3
spring.application.name=consumer-application server.port=8082 eureka.client.register-with-eureka=true eureka.client.serviceUrl.defaultZone=http://localhost:8080/eureka启动类
@SpringBootApplication @EnableDiscoveryClient @EnableFeignClients public class ConsumerApplication { public static void main(String[] args){ SpringApplication.run(ConsumerApplication.class, args); } }Feign 接口 (以下参考网络资料)
@FeignClient(value = "hello-service", configuration = HelloWorld.MultipartSupportConfig.class) public interface HelloWorld { @PostMapping(value = "/upload/file", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) String upload(MultiValueMapControllermultiValueMap); class MultipartSupportConfig{ @Bean @Primary @Scope("prototype") public Encoder feignFormEncoder(ObjectFactory converters) { return new SpringFormEncoder(new SpringEncoder(converters)); } } }
@Controller @Slf4j public class UploadController { @Autowired private HelloWorld helloWorld; @PostMapping("/upload/file") public String upload(UploadBO uploadBO) { File tempFile = null; try{ tempFile = Files.createTempFile("galaxy_file_temp",uploadBO.getFile().getOriginalFilename()).toFile(); uploadBO.getFile().transferTo(tempFile); } catch (IOException ex) { ex.printStackTrace(); } FileSystemResource fileSystemResource = new FileSystemResource(tempFile); log.info("file name is : {}", uploadBO.getFileName()); MultiValueMap提供者 ControllermultiValueMap = new linkedMultiValueMap<>(); multiValueMap.add("file", fileSystemResource); multiValueMap.add("fileName", uploadBO.getFileName()); multiValueMap.add("fileSize", uploadBO.getFileSize()); return helloWorld.upload(multiValueMap);
@Controller @Slf4j public class UploadController { @PostMapping("/upload/file") public String upload(UploadBO uploadBO) { log.info("file name is : {}", uploadBO.getFileName()); File tempFile = null; try{ tempFile = Files.createTempFile("galaxy_file_temp",uploadBO.getFile().getOriginalFilename()).toFile(); log.info("{}", tempFile.getAbsolutePath()); uploadBO.getFile().transferTo(tempFile); } catch (IOException ex) { ex.printStackTrace(); } return "success"; } }
@Data public class UploadBO { private String fileName; private Integer fileSize; private MultipartFile file; }
以上测试通过,但移到公司项目上时却无法成功,经反复测试是由于公司项目上一个服务有多个client,当针对同一个服务的某个feign client配置configuration时,configuration未能生效,由于公司项目不便升级故使用restTemplate发送请求。
https://www.jianshu.com/p/e94fc3ca3295
HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.MULTIPART_FOMR_DATA); HttpEntity requestEntity = new HttpEntity(multiValueMap, headers); restTemplate.postForEntity(url, requestEntity, JSONObject.class, new Object[0]);
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)