在Spring Cloud封裝的Feign中并不直接支持傳文件,但可以通過引入Feign的擴展包來實現,本來就來具體說說如何實現。
服務提供方(接收文件)
服務提供方的實現比較簡單,就按Spring MVC的正常實現方式即可,比如:
@RestControllerpublic class UploadController { @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) public String handleFileUpload(@RequestPart(value = "file") MultipartFile file) { return file.getName(); } }
服務消費方(發送文件)
在服務消費方由于會使用Feign客戶端,所以在這里需要在引入feign對表單提交的依賴,具體如下:
<dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form</artifactId> <version>3.0.3</version></dependency><dependency> <groupId>io.github.openfeign.form</groupId> <artifactId>feign-form-spring</artifactId> <version>3.0.3</version></dependency><dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId></dependency>
定義FeignClient,假設服務提供方的服務名為 upload-server
@FeignClient(value = "upload-server", configuration = TestServiceClient.MultipartSupportConfig.class)public interface UploadService { @PostMapping(value = "/uploadFile", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) String handleFileUpload(@RequestPart(value = "file") MultipartFile file); @Configuration class MultipartSupportConfig { @Bean public Encoder feignFormEncoder() { return new SpringFormEncoder(); } } }
在啟動了服務提供方之后,嘗試在服務消費方編寫測試用例來通過上面定義的Feign客戶端來傳文件,比如:
@Test@SneakyThrowspublic void testHandleFileUpload() { File file = new File("files/aaa.txt"); DiskFileItem fileItem = (DiskFileItem) new DiskFileItemFactory().createItem("file", MediaType.TEXT_PLAIN_VALUE, true, file.getName()); try (InputStream input = new FileInputStream(file); OutputStream os = fileItem.getOutputStream()) { IOUtils.copy(input, os); } catch (Exception e) { throw new IllegalArgumentException("Invalid file: " + e, e); } MultipartFile multi = new CommonsMultipartFile(fileItem); log.info(testServiceClient.handleFileUpload(multi));}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持VeVb武林網。
新聞熱點
疑難解答
圖片精選